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

Java使用split按空格分割字符串仅返回1个元素的问题如何解决

故障根因

  • 代码中使用scanner.next()读取用户输入,该方法默认以空白字符作为终止标记,仅返回第一个空白符前的内容。当用户输入4 6时,itemInfo实际仅存储了字符串"4",因此调用split方法后数组长度为1,访问索引1时会抛出数组越界异常。

修复方法

将输入读取方法替换为scanner.nextLine(),该方法会读取整行输入,包含中间的空格字符,修改后的代码如下:

System.out.println("Enter ItemID ~SPACE~ Quantity: ");
String itemInfo = scanner.nextLine();

String[] selectedItem = itemInfo.split("\\s+",2);

System.out.println(selectedItem.length);
System.out.println("The item selected for order is: " + selectedItem[0] + " and the quantity is: " + selectedItem[1]);

可选优化

为避免用户输入不符合规范(如未输入空格)时抛出异常,可增加数组长度校验逻辑:

if (selectedItem.length < 2) {
    System.out.println("输入格式非法,请按照「商品ID 数量」的格式输入");
    // 可根据业务需求增加重试逻辑
} else {
    System.out.println("The item selected for order is: " + selectedItem[0] + " and the quantity is: " + selectedItem[1]);
}

内容的提问来源于stack exchange,提问作者Chaudhry Talha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:45:04