之前,当我放入if(userChoice == 0)
时,它编译得很好,没有错误。但这是将用户选择设置为无论他们是否点击提款按钮都要不断存款。我需要弄清楚如何将userChoice初始化为键盘输入。我试过userChoice = ();
,但也不起作用。
这是唯一有效的if语句。。。但我的下一个if语句if(userChoice ==1)
仍将存款。??
int userChoice;
String[] menuItems = {"Deposit", "Withdrawal", "Print Account Information", "Exit"};
int selection;
selection = JOptionPane.showOptionDialog(null,
"Please choose an item",
bankAccount,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
menuItems,
"Deposit");
System.out.println(selection);
if (userChoice == 0) {
depositStr = JOptionPane.showInputDialog("Enter your deposit amount: $");
deposit = Double.parseDouble(depositStr);
initialBalance = initialBalance + deposit;
selection = JOptionPane.showOptionDialog(null, "Please choose an item",
bankAccount,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
menuItems,
"Deposit");
System.out.println(selection);
}
然后我有更多的else-if语句,比如else-if(userChoice==1((1又名提款(。。。它从未记录该人命中1
我还有更多的"非此即彼"的陈述。很难在这里保持4个空格的间距。我唯一的编译问题是它说var userChoice没有初始化。
您似乎混淆了userChoice
和selection
,这在本文中是完全相同的。它总是会存款,因为你从来没有设置userChoice
的值,所以如果你初始化为0,它总是0…
JOptionPane.showOptionDialog
将返回所选项目的索引。
因此,您需要此结构并删除userChoice
int selection = JOptionPane.showOptionDialog(... , menuItems, ...);
System.out.printf("You selected %s at position %d%n", menuItems[selection], selection);
if (selection == 0) {
} else if (selection == 1) {
}