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

如何使用Scanner类读取一行空格分隔字符串?代码分割失败求助

Fixing Scanner's String Split Issue After nextInt()

Hey, I spot the exact issue with your code—let me walk you through why it's breaking and how to fix it!

The Root Cause

When you use sc.nextInt() to read the integer t, the Scanner only grabs the numeric characters from your input. It leaves the newline character (the one you type when pressing Enter) unread in the input buffer.

Then when you call sc.nextLine() right after, it doesn't wait for your new input—it just reads that leftover newline character. This makes s an empty string, so splitting it with " " won't give you the array of strings you expect.

Solutions to Fix This

1. Consume the Leftover Newline

Add an extra sc.nextLine() right after nextInt() to "eat" the unused newline:

Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
// This line consumes the newline left by nextInt()
sc.nextLine();
String s = sc.nextLine();
String[] arr = s.split(" ");

2. Read the Integer via nextLine() (More Robust)

Instead of using nextInt(), read the entire line for the integer and convert it to int manually. This avoids any leftover characters entirely:

Scanner sc = new Scanner(System.in);
// Read the whole line and parse to integer
int t = Integer.parseInt(sc.nextLine());
String s = sc.nextLine();
String[] arr = s.split(" ");

3. Use next() Directly for Space-Separated Strings

If your input format has t followed by the space-separated strings on the same line (e.g., 3 cat dog bird), you can skip nextLine() entirely and use next() to grab each string:

Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
String[] arr = new String[t];
// next() automatically skips spaces/newlines to get the next token
for (int i = 0; i < t; i++) {
    arr[i] = sc.next();
}

Bonus Tip

If your input might have multiple consecutive spaces, use split("\\s+") instead of split(" "). This matches any number of whitespace characters (spaces, tabs, newlines) and avoids empty string entries in your array.

内容的提问来源于stack exchange,提问作者Sachin Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 09:52:32