无法退出用于 JOptionPane 的 try-catch 块



我做了一个try-catch块来确保我从JOptionPane获得的输入是正确的,但是当我在JOptionPane上单击取消或关闭时,我无法退出程序,因为我被困在while循环中。

while(value)
{
try
{
players = Integer.parseInt(JOptionPane.showInputDialog("Would you like to start a two-player(enter 2) or three-player(enter 3) game?"));
value = false;
if(players != 2 && players != 3)
throw new InputMismatchException();
}
catch(InputMismatchException e)
{
JOptionPane.showMessageDialog(null, "Not a valid input.");
value = true;
}
catch(NumberFormatException f)
{
JOptionPane.showMessageDialog(null, "Not a valid input.");
value = true;
}
if(players == JOptionPane.CANCEL_OPTION || players == JOptionPane.CLOSED_OPTION)
value = false;
}

退出程序的任何提示?

为什么不使用选项窗格中的组合框来允许用户选择玩家数量?

然后,您知道数据将始终有效,您只需要处理"是/否"按钮。

阅读 Swing 教程中有关如何制作对话框的部分,了解此方法的示例。

这是我给你的解决方案。如果您需要任何帮助,请告诉我。

import javax.swing.*;
public class Status {
public static void main(String[] args) {
boolean value = true;
int players = 0;
String input;
while (value) {
input = JOptionPane.showInputDialog("Would you like to start a two-player(enter 2) or three-player(enter 3) game?");
//exits the loop if the user closes the window or presses cancel
if (input == null)
break;
//if a user doesn't enter a number display error message
try {
players = Integer.parseInt(input);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Not a valid input.");
}
//if a user enters an invalid number display error message
if (players != 2 && players != 3) {
JOptionPane.showMessageDialog(null, "Not a valid input.");
} else {
value = false;
}

}
}
}

最新更新