首页 > 解决方案 > 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它时给我46索引01

标签: javastringsplit

解决方案


您只需更改scanner.next()为即可scanner.nextLine()


推荐阅读