java - While 循环问题(Java)

标签 java while-loop numberformatexception

我正在尝试制作一个 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);
    }

数字格式异常

    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)

最佳答案

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

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

关于java - While 循环问题(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16427315/

相关文章:

java - 应用程序崩溃了几次但不是在 Debug模式下

java - <s :fileUpload> is returning null value

java - ListSelectionListener 无法识别 if 条件中的联合

php - 虽然循环 PHP get_result 不工作

java.lang.NumberFormatException : Invalid int: "1"

java - JFormatedTextField DocumentListener 引发 java.lang.IllegalStateException

java - 处理输入扫描器引起的异常

java - 将数据从 JSP 动态地从 HTML 页面传递到 Servlet

python - 在Python中使用break进入异常错误处理可以吗?

loops - Racket 中的 While 循环