如何允许方法两次访问号码

时间:2016-11-15 23:54:13

标签: java methods

当我拨打提款/存款方式时,我很难让余额保持更新。即时通讯询问我如何存储数字并保持不变,以便我可以通过多次方法调用来更新它。

这是主要代码段

public void savingsWithdraw(){
    System.out.print("Enter withdraw amount: ");
    Scanner w = new Scanner(System.in);
    double amount = w.nextDouble();
    Savings with = new Savings();
    with.withdraw(amount);
    System.out.println("Savings Balance is: " + with.getBalance());
    mainMenu();
}

这是子类

public class Savings
 {
    double balance =0;
    public void deposit(double amount){
      balance=balance+amount;
 }
    public void withdraw(double amount){
      balance=balance-amount;
 }
    public double getBalance(){
      return balance;
  }

}

2 个答案:

答案 0 :(得分:0)

Savings with = new Savings();

这一行几乎表明每次调用savingsWithdraw()方法时都会创建一个新的Savings对象,从而导致余额始终保持为零。尝试在方法之外创建一个Savings对象,然后只使用该Savings对象进行调用。

或者更好的设计可能如下所示:

public void savingsWithdraw(Savings account){
    System.out.print("Enter withdraw amount: ");
    Scanner w = new Scanner(System.in);
    double amount = w.nextDouble();
    account.withdraw(amount);
    System.out.println("Savings Balance is: " + account.getBalance());
    mainMenu();
}

每次调用该函数时,这仍然会消除Saves对象的重新创建。

答案 1 :(得分:0)

正如@Jurko和@Jonny所述;使用

行创建一个新的Savings对象
Savings with = new Savings();

每个Savings对象都将拥有自己的double balance,这意味着如果您创建一个Saving对象,则存入500,该对象将拥有500的余额货币。然后你创建另一个对象,那个对象的余额将为0.

可以通过让一个单独的对象一直工作来轻松解决,而不是每次存取款都创建一个实例。

另一个非常简单的解决方案,如果你想坚持创建对象,虽然这不是性能建议。使您的余额变量为静态,如下所示:

static double balance = 0;

这样,所有Savings对象将共享相同的余额变量。

另外一个提示是关闭扫描仪以避免内存泄漏:

w.close();