首页 > 解决方案 > 为什么scanner.nextInt() != 0 不起作用?

问题描述

我试图弄清楚为什么这不能正常工作,我很困惑。

Scanner scanner = new Scanner(System.in);
        while(!scanner.hasNextInt() || scanner.nextInt() != 0) {
            System.out.println("Wrong!");
            scanner.next();
        }
        return scanner.nextInt();

如果我输入除 0 以外的任何内容,则上面的代码正确打印输出错误,但在输入 0 时它不会立即终止。相反,我输入 0 一次,然后任何与我之后输入的内容类似的内容都会卡住。

Input: 1, Output: Wrong!
Enter: 0, Output: Nothing

直到我再输入 0 两次后,程序才会终止。

我确实有一个问题,为什么这有效

while(!scanner.hasNextInt() && list.size() > scanner.nextInt()) {
        validation();               //Call invalid message function
        scanner.nextInt();          //Record user input, integer
    }
    return scanner.nextInt() - 1;   //Return user input 

标签: javajava.util.scanner

解决方案


Scanner scanner = new Scanner(System.in);
        while(!scanner.hasNextInt()/*here*/ || scanner.nextInt() != 0) {
            System.out.println("Wrong!");
            scanner.next(); // this is also wrong
        }
        return scanner.nextInt();//this is what is wrong

scanner.next()正在发生的事情是nextInt()等待扫描器返回一个值,所以所有这些额外的东西都会导致扫描器等待你满足它的请求。您在 while 循环之后向扫描仪询问另一个整数,解决方案是:

Scanner scanner = new Scanner(System.in);
        int i = 0;
        while((i = scanner.nextInt()) != 0) {
            System.out.println("Wrong!");
        }
        return i;

也仅在需要时返回一个数字,此方法非常适用于根本不需要返回任何内容的“void”函数。


推荐阅读