【问题标题】:Confusion with an infinite while loop, concerning Scanner.nextInt();与 Scanner.nextInt() 相关的无限 while 循环混淆;
【发布时间】:2015-11-09 14:50:02
【问题描述】:

我无法理解为什么代码不起作用。我的目标是继续阅读用户的输入,直到用户最终输入“5”,代码将继续输入。 我很欣赏可能有更好的方法,并且愿意接受更简洁的方法来解决这个问题(也许是尝试解析一个字符串),但是我的问题是为什么我的方法不起作用而不是寻找更好的方法。

当输入任何整数时,代码都能完美运行,但是如果我要输入字符串,代码会不断循环,并且始终启动 catch 块而无需任何输入。我认为这是扫描仪保留我的输入的一个功能,但我不确定。

我的代码如下:

import java.util.Scanner;
import java.util.InputMismatchException;

public class App {
    public static void main(String[] args) {

        int temp = 0;
        System.out.println("Enter the number 5: ");

        while (temp != 5) {
            try {
                temp = sc.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Try again!");
            }
        }
        System.out.println("Got it!");
        sc.close();
    }
}

【问题讨论】:

    标签: java loops input while-loop


    【解决方案1】:

    如果接下来要读取的不是整数,则nextInt 不会读取任何内容。所以如果你输入“hi”,那么nextInt 会抛出一个InputMismatchException,然后你的程序会再次调用nextInt那个调用仍然会抛出InputMismatchException,因为接下来要读取的内容仍然是“hi”,它不是整数。然后您的程序再次调用nextInt,并且出于完全相同的原因再次引发异常。以此类推。

    一种可能的解决方案是调用sc.next(),然后忽略结果:

            try {
                temp = sc.nextInt();
            } catch (InputMismatchException e) {
                sc.next(); // ignore whatever the user typed that wasn't an integer
                System.out.println("Try again!");
            }
    

    【讨论】:

    • 这行得通,我同意你的回答,但是如果我要输入一个字符串,其中 x 个不同的单词至少用一个空格分隔(例如,我回复“测试一二三”,sc .next() 只跳过其中一个单词,然后再次读取三个 rest,然后导致 catch 执行四次而不是一次。有没有办法避免这种情况?
    • 啊,将其更改为 sc.nextLine() 效果很好。谢谢!
    【解决方案2】:

    正确的代码版本应该是这样的。 Scanner 不知道是否输入 Int。让我们读取行并解析它并检查它是否为整数然后继续。

    import java.util.Scanner;
    import java.util.InputMismatchException;
    
    public class App {
        public static void main(String[] args) {
    
            int temp = 0;
            System.out.println("Enter the number 5: ");
        Scanner sc = new Scanner(System.in);
            while (temp != 5) {
                try {
            String str = sc.nextLine();
                    temp = Integer.parseInt(str);
                } catch (NumberFormatException e) {
                    System.out.println("Try again!");
                }
            }
            System.out.println("Got it!");
            sc.close();
        }
    }
    

    【讨论】:

      【解决方案3】:

      这是我认为正在发生的事情:

      1. 当您输入int 时,一切正常。 sc.nextInt(); 能够将输入解析为有效的整数值。
      2. 当您输入字符串时,sc.nextInt(); 会抛出异常,因为输入字符串不是有效的整数值。
      3. 现在在您的代码中,如果输入的值不是整数,则循环将永远不会中断,因为它的 (temp != 5) 始终为真,因此循环无限重复。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-13
        • 2012-01-02
        • 1970-01-01
        • 2013-03-18
        • 2023-02-02
        • 1970-01-01
        • 2015-06-25
        • 2014-03-29
        相关资源
        最近更新 更多