首页 > 解决方案 > 如果扫描仪接收到 int 以外的内容,则会创建无限循环

问题描述

在这个 java 方法中,重点是让扫描仪接收最小值和最大值之间的 int。如果接收到超出这些范围的int ,则程序会正确输出“无效输入”。但是,如果输入诸如“g”或“h”之类的内容或 int 以外的内容,则会创建一个无限循环。

我试图在代码中的多个位置重新初始化扫描仪,但看起来当从 System.in 输入除 int 以外的其他内容时,它只是再次通过扫描仪飞行并保持循环继续进行。有什么想法吗

public static int promptInt(int min, int max) {
    while (false != true) {
        int b = 0;
        Scanner scnr = new Scanner(System.in);
        System.out.print("Choose a value between " + min + " and " + max + ": ");
        if (scnr.hasNext()) {
            if (scnr.hasNextInt()) {
                b = scnr.nextInt();
                if (b <= max) {
                    return b;
                } else {
                    System.out.println("Invalid Value");
                }
            }
            else if (scnr.hasNextInt() == false) {
                System.out.println("Not an Int");

            }
        }
    }
}

标签: javajava.util.scanner

解决方案


根据上面的一些评论,需要 scnr.next() 否则它会继续检查已初始化的第一个扫描仪。这是现在起作用的修改后的代码。

public static int promptInt(int min, int max) {
    Scanner scnr = new Scanner(System.in);
    while (false != true) {
        int b = 0;
        System.out.print("Choose a number between " + min + " and " + max + ": ");
        if (scnr.hasNext()) {
            if (scnr.hasNextInt() == false) {
                System.out.println("Invalid value.");
                //the scnr.next was needed here
                scnr.next();
            }
            else {
                b = scnr.nextInt();
                if (b <= max) {
                    return b;
                } else {
                    System.out.println("Invalid value.");
                }  
            }
        }
    }
}

推荐阅读