Java Scanner连续调用hasNext()输入异常:添加next()后为何可重复输入?
Why do these two Scanner code snippets require different input times?
Great question! Let's break down what's happening here with Java's Scanner class—this all comes down to how hasNext() and next() handle the input buffer differently.
First, let's clarify the key behaviors of these two methods:
hasNext()is a check-only method: it looks into the input buffer to see if there's a valid token (like your input1) available to read. Crucially, it does NOT remove or consume any content from the buffer. It just says "yes, there's something here" or "no, wait for more input".next()is a consuming method: it reads the next valid token from the buffer, and then removes that token from the buffer so it can't be read again.
Let's walk through Scenario 1
Your code:
Scanner sc = new Scanner(System.in); System.out.println(sc.hasNext()); System.out.println(sc.hasNext());
Here's the play-by-play when you input 1:
- When you type
1and press enter, the input buffer gets filled with1\n(the number plus a newline character). - First
hasNext()call: It checks the buffer, sees the valid token1, returnstrue—and leaves1in the buffer. - Second
hasNext()call: It checks the buffer again, and1is still there! So it returnstrueagain, no need for new input.
Now Scenario 2
Your modified code:
Scanner sc = new Scanner(System.in); System.out.println(sc.hasNext()); System.out.println("str -> " + sc.next()); System.out.println(sc.hasNext());
Here's what happens when you first input 1:
- Input
1fills the buffer with1\n. - First
hasNext(): Finds1in the buffer, returnstrue, doesn't touch it. next()call: Reads the1token, removes it from the buffer. Now the buffer only has the leftover newline character (whichScannertreats as whitespace, not a valid token).- Third
hasNext()call: It checks the buffer, and there's no valid token left (just whitespace). SoScannerblocks and waits for you to input something new—hence why you have to type1a second time to get it to returntrue.
That's the core difference: hasNext() doesn't touch the input, but next() eats the token, leaving the buffer empty of valid content for the next check.
内容的提问来源于stack exchange,提问作者Garmin
相关产品推荐
相关产品推荐

