java - Java拆分字符串在拆分后仅保留一个字符
问题描述
我有一个简单的代码:
System.out.println("Enter ItemID ~SPACE~ Quantity: ");
String itemInfo = scanner.next();
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]);
假设用户输入4 6
然后打印语句打印1
然后一个错误Exception in thread "main" java.lang
基本上意味着selectedItem[1]
不存在或为空。
我的问题是如何拆分字符串,以便当用户输入4 6
它时给我4
和6
索引0
和1
?
解决方案
您只需更改scanner.next()
为即可scanner.nextLine()
。
推荐阅读
- kubernetes - 在 Kubernetes 集群上缺少共识的实际后果?
- javascript - node.js SyntaxError:无效或意外的令牌
- python-3.x - 将类实例存储在 python 列表中
- javascript - 如何根据 JSON 文件中的布尔值自动添加过滤器
- function - 映射函数应用于列表的特定元素
- ffmpeg - 如何使用 ffmpeg 查找音频流
- java - 模拟firebase android应用程序
- python - 在 IBM Watson Studios 上加载 json 文件
- flutter - 如何在不显示键盘的情况下聚焦 TextField?
- java - 从数据库表中填充 Java HashMap