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

Scanner类处理字符串"1 a 10 . 100 sfn 1000"的面试程序问题

Great question—this gets to how Java's Scanner class handles tokenization and type parsing, which is a common pitfall in interviews. Let's break this down clearly.

How Scanner Works with Your Input String

First, let's recap the key behavior of Scanner for this scenario:

  • By default, Scanner splits input into tokens using any whitespace character (spaces, newlines, tabs, etc.) as the delimiter. For your string "1 a 10 . 100 sfn 1000", the tokens are: "1", "a", "10", ".", "100", "sfn", "1000".
  • When you call nextInt(), Scanner doesn't "skip" invalid tokens—it tries to parse the next available token as an integer. If that token can't be converted to an int (like a letter or punctuation), it throws an InputMismatchException immediately.
  • The only way to skip invalid tokens is to first check if the next token is an integer with hasNextInt(), which will advance the scanner past non-integer tokens until it finds a valid one (or reaches the end of input).

What Happens When Your Code Runs

Let's walk through the loop step by step:

  1. First iteration: scan.nextInt() reads the first token "1", which is a valid integer. total becomes 0 + 1 = 1.
  2. Second iteration: The scanner moves to the next token, which is "a". When it tries to parse this as an integer, it can't—so it throws an InputMismatchException. The program crashes immediately; the third and fourth iterations never run, and System.out.println(total) never executes.

If you wanted to sum all the valid integers without crashing, you'd modify the code to check for valid integers first, like this:

String test = "1 a 10 . 100 sfn 1000";
Scanner scan = new Scanner(test);
int total = 0;
while (scan.hasNextInt()) {
    total += scan.nextInt();
}
System.out.println(total); // Outputs 1111

But with your original code, the result is an exception, not a printed total.

内容的提问来源于stack exchange,提问作者pratiksha jadhav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:29:27