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

时间:2018-05-20 18:55:36

标签: java swing try-catch joptionpane

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

     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;

     }

退出该计划的任何提示?

2 个答案:

答案 0 :(得分:1)

为什么不在选项窗格中使用组合框来允许用户选择播放器数量?

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

阅读How to Make Dialogs上Swing教程中的部分,了解此方法的示例。

答案 1 :(得分:-1)

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

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;
        }


    }
  }
}