You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 input 1) 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:

  1. When you type 1 and press enter, the input buffer gets filled with 1\n (the number plus a newline character).
  2. First hasNext() call: It checks the buffer, sees the valid token 1, returns true—and leaves 1 in the buffer.
  3. Second hasNext() call: It checks the buffer again, and 1 is still there! So it returns true again, 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:

  1. Input 1 fills the buffer with 1\n.
  2. First hasNext(): Finds 1 in the buffer, returns true, doesn't touch it.
  3. next() call: Reads the 1 token, removes it from the buffer. Now the buffer only has the leftover newline character (which Scanner treats as whitespace, not a valid token).
  4. Third hasNext() call: It checks the buffer, and there's no valid token left (just whitespace). So Scanner blocks and waits for you to input something new—hence why you have to type 1 a second time to get it to return true.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:53:10