我是Java的新手,我只想显示一条错误消息,如果用户从键盘上按转义键或单击showInputDialog
的X按钮或按取消程序正常关闭,
就像现在如果我关闭或取消输入对话框,它会给出以下错误
Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:11)
我也尝试抛出异常 JVM,但它没有按预期工作,这是我的代码:
String userInput;
BankAccount myAccount = new BankAccount();
while (true){
userInput = JOptionPane.showInputDialog("1. Withdrawn2. Depositn3. View Balancen4. Exit");
switch (userInput){
case "1":
myAccount.withdraw(Integer.parseInt(JOptionPane.showInputDialog("Please Enter ID: ")),Double.parseDouble(JOptionPane.showInputDialog("Please Enter Amount to Withdraw: ")));
break;
case "2":
myAccount.deposit(Integer.parseInt(JOptionPane.showInputDialog("Please Enter ID: ")),Double.parseDouble(JOptionPane.showInputDialog("Please enter Amount to Deposit: ")));
break;
case "3":
myAccount.viewBalance(Integer.parseInt(JOptionPane.showInputDialog("Please Enter ID: ")));
break;
case "4":
myAccount.exit();
System.exit(0);
default:
JOptionPane.showMessageDialog(null,"Invalid InputnPlease Try Again");
break;
}
}
我只想在用户单击 X 或取消提示时显示错误消息,我该如何捕获它? 所以我将在那里实现我的逻辑
JOptionPane.showInputDialog 返回 null,而不是字符串,如果用户单击"x"或"取消"按钮。 所以代替:
while (true){
userInput = JOptionPane.showInputDialog("1. Withdrawn2. Depositn3. View Balancen4. Exit");
switch (userInput){
case "1": ...
您可能希望执行以下操作:
while (true){
userInput = JOptionPane.showInputDialog("1. Withdrawn2. Depositn3. View Balancen4. Exit");
if (userInput == null) {
JOptionPane.showMessageDialog(null, "Invalid InputnPlease Try Again", "Cannot Cancel", JOptionPane.ERROR_MESSAGE);
continue;
}
switch (userInput){
case "1": ...
这将捕获 cancel/'x' 的情况,并且 continue 将让它跳到 while 循环的下一次迭代,而不是在尝试使用带有 null 的 switch 语句时抛出错误。