如果扫描仪收到的不是整数

时间:2018-10-25 17:21:16

标签: java java.util.scanner

在此java方法中,要点是扫描程序可以在最小值和最大值之间接收一个整数。如果收到的 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");

            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

根据上面的一些评论,需要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.");
                }  
            }
        }
    }
}
相关问题