我正在制作一个模拟银行交易的程序。我必须询问用户是否要存款、取款或转账。
当我存入一定金额(例如 1000)时,它说我的余额是 1000。然后我要求提取一个像 400 这样的数字,它说我的余额是 -400。毕竟我想也许我必须检查我的余额,然后它会给我正确的余额,应该是 600,但它显示的是 0。例如,看这个成绩单:
我在想,因为在我的代码中(如下所示)我设置了 balance = 0 但是如果我把 = 0 拿走并尝试运行程序,它说它需要初始化。
我被困住了,我想弄清楚。请不要发布更正的整个代码。我想自己修复它并学习!
import java.util.Scanner;
public class BankTransactions {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num;
do {
double balance = 0;
double amount;
System.out.println("Type Number");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance");
System.out.println("4. Exit");
num = scan.nextInt();
if (num == 1) {
System.out.println("Enter amount to deposit: ");
amount = scan.nextDouble();
// Add the amount to the balance
balance += amount;
System.out.println("Your balance is");
System.out.println(balance);
} else if (num == 2) {
System.out.println("Enter amount to withdrawal: ");
amount = scan.nextDouble();
// Remove the amount from the balance
balance -= amount;
System.out.println("Your balance is");
System.out.println(balance);
} else if (num == 3) {
System.out.println("Your Balance");
System.out.println(balance);
}
} while (num != 4);
System.out.println("Good Bye!");
}
}