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,
Scannersplits 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(),Scannerdoesn't "skip" invalid tokens—it tries to parse the next available token as an integer. If that token can't be converted to anint(like a letter or punctuation), it throws anInputMismatchExceptionimmediately. - 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:
- First iteration:
scan.nextInt()reads the first token"1", which is a valid integer.totalbecomes0 + 1 = 1. - 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 anInputMismatchException. The program crashes immediately; the third and fourth iterations never run, andSystem.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
相关产品推荐
相关产品推荐

