gpt4 book ai didi

java - 如何更改不同类的主方法中的值

转载 作者:太空宇宙 更新时间:2023-11-04 12:08:22 25 4
gpt4 key购买 nike

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

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;

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

抱歉,代码量较大,希望大家理解我的问题并提供帮助!

最佳答案

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

关于java - 如何更改不同类的主方法中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40112148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com