有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果扫描器接收到除int以外的内容,则会创建java无止境循环

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

我试图在代码中的多个位置重新初始化扫描仪,但看起来像是从系统中输入了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) 个答案

  1. # 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.");
                    }  
                }
            }
        }
    }