如何从不同的类中改变main方法的值

时间:2016-10-18 15:22:47

标签: java methods

我正在创建一个具有ATM类的程序,其中有一个cheqings和储蓄帐户,可以根据用户在起始类的main方法中输入的内容进行更改。出于某种原因,当用户输入存款/退出账户的金额时,数学已完成,但不存储该值。因此,当我去显示帐户余额时,两个帐户都处于起始值。

public class ATM {

private double cheqBal;
private double savingsBal;
private String bankName;

public ATM(double cheq, double savings, String name) {
    cheqBal = cheq;
    savingsBal = savings;
    bankName = name;
}

public double getCheq() {
    return cheqBal;
}
public double getSavings() {
    return savingsBal;
}
public String getName() {
    return bankName;
}

public void setCheq(double cheq) {
    cheqBal = cheq;
}
public void setSavings(double savings) {
    savingsBal = savings;
}
public void setName(String name) {
    bankName = name;
}

public double depositCheq(double cheq) {
    if (cheq < 0) {
        System.out.println("Sorry you cannot do that!");
    } else {
        cheqBal += cheq;
    }
    System.out.println(getCheq());
    return cheqBal;
}

存在ATM类,其中存款/取款的方法是。我只展示了存款支票方法。

double savBal = 500;
        double cheqBal = 1000;

        ATM bank1 = new ATM(cheqBal, savBal, "BMO");

        String userChoice = JOptionPane.showInputDialog("1: Deposit Cheqings \n2: Deposit Savings \n"
                + "3: Withdraw Cheqings \n4: Withdraw Savings \n5: Show Balance\n6: Exit");
        int choice = Integer.parseInt(userChoice);

        if (choice == 1) {
            String cheqIn = JOptionPane.showInputDialog("How much would you like to deposit?: ");
            bank1.depositCheq(Double.parseDouble(cheqIn));
            cheqBal = bank1.getCheq();
        } else if (choice == 2) {
            String savIn = JOptionPane.showInputDialog("How much would you like to deposit?: ");
            bank1.depositSavings(Double.parseDouble(savIn));
            savBal = bank1.getSavings();
        } else if (choice == 3) {
            String cheqOut = JOptionPane.showInputDialog("How much would you like to withdraw?: ");
            bank1.withdrawCheq(Double.parseDouble(cheqOut));
            cheqBal = bank1.getCheq();
        } else if(choice == 4){
            String savOut = JOptionPane.showInputDialog("How much would you like to withdraw?: ");
            bank1.withdrawSavings(Double.parseDouble(savOut));
            savBal = bank1.getSavings();
        }else if(choice == 5){
            bank1.toString();
        }else if(choice == 6){
            break;

有主要方法。当我点击1来存钱时,它没有重复我在我点击5以显示余额时存入的金额。 (所有主要方法都在一个循环中,所以它一直持续到退出)。

对于大量的代码感到抱歉,希望你们能理解我的问题并提供帮助!

1 个答案:

答案 0 :(得分:0)

每次运行循环时都会构造一个新的ATM对象,并将起始值传递给构造函数,因此您将显示此新对象的值,旧对象将被销毁。