我目前有一个具有存款方法的帐户类。 每当我调用此方法时,它都会将总金额重新初始化为零,然后添加添加的金额,因此总金额始终设置为添加的金额。
帐户类别:
public class Accounts {
double totalAmount;
public Accounts(){
totalAmount = this.totalAmount;
}
public double Deposit(double amountAdded) {
totalAmount+=amountAdded;
return totalAmount;
}
调用main中的方法:
System.out.println("Please enter the customer's account number you want to deposit money for");
int accountNumber = input.nextInt();
while(accountNumber == 0 || accountNumber < 0){
System.out.println("Please enter an account number greater than 0");
accountNumber = input.nextInt();
}
try{
for(int i = 0; i < index +1 ; i++){
if(cust[i].accountNumber1 == accountNumber){
System.out.println("Please enter the amount you want to deposit");
double amount = input.nextDouble();
acc[i] = new Accounts();
double a = acc[i].Deposit(amount);
System.out.println(a);
break;
}
}
假设 x 人的当前总金额为 100。当调用方法 Deposit 并额外添加 300 时,该方法将返回 100,而不是预期的 400。
最佳答案
您创建一个新帐户,而不是使用数组中的帐户。
acc[i] = new Accounts();
这会覆盖数组中的帐户,并且新创建的帐户的余额为 0。
关于java - 方法是将我的变量重新初始化为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53621797/