JOptionPane / Try / If / OR问题

时间:2014-04-08 15:26:02

标签: java exception try-catch joptionpane

我似乎遇到了代码问题。我正在尝试为我的Java类创建一个Rock,Paper,Scissors游戏。它需要此JOptionPane输入类型,并且还需要try catch来处理异常。输入选项也是一项要求。我找不到我的代码有什么问题,我甚至添加了一个有问题的值的System.out.println,以确认它是传递给if语句时的正确输入。问题是无论输入是什么,正确还是不正确,总是抛出不正确输入的异常。是的,我知道运行这最终成为无限循环,只能通过任务管理器终止进程来关闭。它只是所有代码的片段。

我使用Eclipse Juno Build id:20120614-1722在运行JavaSE-1.6的Windows 7 64位机器上编译和运行我的代码。

public static void main(String args[]){
    String input;
    int counter = 0;
    int inputnum;
    boolean valid = false;
    do
    {

        try {
            input = JOptionPane.showInputDialog("What is your choice?\n\nRock: (0,r,rock)\nPaper: (1,p,paper)\nScissors: (2,s,scissors)\nLizard: (3,l,lizard)\nSpock: (4,o,spock)");
            System.out.println(input);
            if (input == "0" || input == "r" || input =="rock"){
                inputnum = 1;
                valid = true;
                counter += 1;
            }
            else if (input == "1" || input == "p" || input == "paper"){
                inputnum = 2;
                valid = true;
                counter += 1;
            }
            else if (input == "2" || input == "s" || input == "scissors"){
                inputnum = 3;
                valid = true;
                counter += 1;
            }
            else if (input == "3" || input == "l" || input == "lizard"){
                inputnum = 4;
                valid = true;
                counter += 1;
            }
            else if (input == "4" || input == "o" || input == "spock"){
                inputnum = 5;
                valid = true;
                counter += 1;
            }
            else {
                throw new IllegalArgumentException("Invalid Input!");
            }
        }
        catch (IllegalArgumentException e){
            inputnum = 0;
            JOptionPane.showMessageDialog(null, "Invalid input! Try again!");
        }
        catch (Exception e){
            inputnum = 0;
            JOptionPane.showMessageDialog(null, "Unexpected Exception! Try again!");
        }





    } while (valid == false);

}

0 个答案:

没有答案