我有一個非常長的問題。我正在創建一個銀行賬戶,並將餘額設置爲0.如果用戶選擇提取或向賬戶存入資金,餘額不會改變。我選擇顯示餘額,它仍然表示0.這可能是一個沒有道理的但我現在已經花了。這裏是我的長碼(switch語句是在我的主類和方法在一個對象類):Java不讀取用戶修改後傳遞給它的變量
public class MyProgram2{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in);
String menu, outputString, poo;
int option = 1;
int id = 0;
double balance = 0, amount = 0;
Account acc = new Account();
menu ="\n\t1 Create Account and ID" +
"\n\t2 Check balance" +
"\n\t3 Withdraw" +
"\n\t4 Deposit" +
"\n\t5 Get account ID" +
"\n\t6 Display Account Info" +
"\n\t0 Quit\n\n\n";
System.out.println(menu);
System.out.println("\tEnter your selection: ");
option = scan.nextInt();
while (option != 0) {
switch (option) {
case 1: //Create an account and set ID
System.out.print("Enter Your Account ID to create account:\t");
id = input.nextInt();
System.out.println("Account created!");
break;
case 2: //check balance
acc.checkBalance(balance);
break;
case 3: //withdraw money
acc.withdraw(balance, amount);
break;
case 4: //deposit money
acc.deposit(balance, amount);
break;
case 5: //get account id
acc.getID(id);
break;
case 7: //display account info
System.out.print("option 7");
break;
default: outputString = "\nInvalid Selection\n";
System.out.println(outputString);
break;
}
System.out.println(menu);
System.out.print("\tEnter your selection: ");
option = scan.nextInt();
}
這些都是我打電話的方法:
public class Account{
Scanner input = new Scanner (System.in);
public Account(){
}
public void getID(int id){
System.out.println("Your account ID is:\t" + id);
}
public void checkBalance(double balance){
System.out.println("Your balance is:\t$" + balance);
}
public double withdraw(double amount, double balance){
System.out.println("How much do you want to withdraw?:\t$");
amount = input.nextDouble();
balance -= amount;
return balance;
}
public double deposit(double amount, double balance){
System.out.println("How much do you want to deposit?:\t");
amount = input.nextDouble();
balance += amount;
return balance;
}
public void getAccountInfo(int id, double balance){
}
}
另一種方法是,如果需要傳遞參考效果,可以創建一個帶有單個公共字段的「DoubleHolder」對象。 +1爲了使這個絕對清楚。 –
我已經退回餘額...應該改變什麼? – Josh
您正在返回餘額,但完全沒有使用返回值,因此該值沒有更新。我將用示例代碼 – momo