在分配给 int 变量之前检查用户输入(扫描器)


int i;
Scanner scan = new Scanner(System.in) {
i = scan.nextInt();
}

我想做的是在用户输入字符而不是整数时捕获扫描仪中的错误。我尝试了下面的代码,但最终调用了另一个用户输入(例如,在验证仅数字的第一次扫描后,调用另一个scan.nextInt((将值分配给i(:

int i;
Scanner scan = new Scanner(System.in) {
    while (scan.hasNextInt()){
    i = scan.nextInt();
    } else {
    System.out.println("Invalid input!");
    }
}

你的逻辑似乎有点不对劲,如果输入无效,你必须消耗输入。此外,您的匿名块似乎很奇怪。我想你想要类似的东西

int i = -1; // <-- give it a default value.
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) { // <-- check for any input.
    if (scan.hasNextInt()) { // <-- check if it is an int.
        i = scan.nextInt(); // <-- get the int.
        break; // <-- end the loop.
    } else {
        // Read the non int.
        System.out.println("Invalid input! " + scan.next()); 
    }
}

最新更新