简体   繁体   中英

Why does scanner.nextInt() != 0 not work?

I'm trying to figure out why this isn't working properly and I am puzzled.

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

The above code correctly prints out wrong if I enter anything except 0 but it does not terminate immediately upon entering 0. Instead, I enter 0 once, and then anything it's like anything I enter after is stuck.

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

The program does not terminate until after I enter 0 two more times.

I do have a question though, why this works

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 
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

what is happening is scanner.next() and nextInt() wait for the scanner to return a value, so all of these extras will cause the scanner to wait for you to satisfy its requests. you are asking the scanner for another integer AFTER the while loop, a solution would be this:

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

also return a number only if you need, this method is perfectly applicable for a 'void' funtion where nothing needs to be returned at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM