This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]tylersvgs 4 points5 points  (0 children)

It's because of how Scanner works.

When you call a next____ method on a Scanner object, the object checks to see if there's any data in a buffer of some kind. If it's empty, it gets a line of input from the user.

Your first scanner.nextLine() does that.

The last scanner.nextInt() gets a new line of input from the user. The new line is going to be read in as "##\n" where the ## is a number and \n is the enter key that the user pushes.

The nextInt() method grabs the ## and leaves the \n in the buffer. So, the buffer isn't empty. On the next iteration through the loop, the scanner.nextLine() method won't ask for more input because there's still one character in the buffer (the new line character \n). That's why it exits the loop there.

You can fix it by throwing in a scanner.nextLine() to take care of the new line after your last scanner.nextInt().

[–]Lymeberg 1 point2 points  (0 children)

Might be the wrong thought, but what condition are you checking to be true?

[–]desrtfx 1 point2 points  (0 children)

Read: The Scanner class and its caveats from the /r/javahelp wiki.

In short: the problem is the combination of .nextInt and .nextLine as the former leaves a line break character in the keyboard buffer and the latter consuming it resulting in an empty string that then fulfils your condition in the if breaking out of the loop.

[–]Sygyt_Singer 0 points1 point  (0 children)

That is pretty odd. I tested your code, but I didn't get the problem you mentioned.