【问题标题】:While Loop issue (Java)While 循环问题 (Java)
【发布时间】:2013-05-07 19:48:55
【问题描述】:

我正在尝试创建一个 while 循环,提示用户在使用无效条目时重新输入数据。在我的程序中,我要求用户输入一个数字(0-3),所以如果他们输入除此之外的任何内容,我希望弹出一条错误消息,要求他们重新输入他们的数据。我不知道我在循环中做错了什么。无论我输入什么,我总是会收到错误消息。

String itemChoice = JOptionPane.showInputDialog(null, itemList);
    itemChoiceNum = Integer.parseInt(itemChoice);

    //test to make sure the input is valid
    while (itemChoiceNum != 0 || itemChoiceNum != 1 || itemChoiceNum != 2 || itemChoiceNum != 3) {
        JOptionPane.showMessageDialog(null, "Sorry that's not a valid choice. Please start again.");
        itemChoice = JOptionPane.showInputDialog(null, itemList);
    }

NumberFormatException

    while (itemChoiceNum != 0 && itemChoiceNum != 1 && itemChoiceNum != 2 && itemChoiceNum != 3) {
        try {
            JOptionPane.showMessageDialog(null, "Sorry that's not a valid choice. Please start again.");
                                        itemChoice = JOptionPane.showInputDialog(null, itemList);
                                        itemChoiceNum = Integer.parseInt(itemChoice);
        }

        catch (NumberFormatException itemChoiceNum ) {
            JOptionPane.showMessageDialog(null, "Sorry that's not a valid choice. Please start again.");
        }

错误

Exception in thread "main" java.lang.NumberFormatException: For input string: "f"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at VendingClass.displayVend(VendingClass.java:82)
    at VendingMachineDemo.main(VendingMachineDemo.java:12)

【问题讨论】:

    标签: java while-loop numberformatexception


    【解决方案1】:

    你的逻辑不正确。选择不是 0 它不是 1 它不是 2 总是正确的;你想用 && 运算符“和”。

    while (itemChoiceNum != 0 && itemChoiceNum != 1 && itemChoiceNum != 2 && itemChoiceNum != 4) {
    

    【讨论】:

    • 跟进,有没有办法在用户输入字符串时也显示错误信息?当我输入一个字符串时,程序崩溃了。
    • 捕捉Integer.parseInt 抛出的NumberFormatException 并向用户显示带有相应错误消息的消息对话框。
    • 我做对了吗?我用我添加的内容更新了我的问题。
    • 当我输入一封信时它仍然崩溃。我将错误添加到我的问题中。
    【解决方案2】:

    在 while 条件下使用 should && 而不是 ||。目前它始终返回 True。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 2014-05-27
      • 2016-01-03
      • 1970-01-01
      相关资源
      最近更新 更多