我试图使用split方法将输入与控制台分离,然后将每个值放入单独的容器中,并且继续出现此错误:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
。我认为问题是它忽略了第一个空格之后的输入,但是对于为什么以及如何解决它我一无所知。
有人可以告诉我我在做什么错,并建议我应该怎么做,以便将空格后的文本存储在我的容器中吗?预先谢谢你。
Scanner s = new Scanner(System.in);
System.out.println("Input the name and phone no: ");
String text = s.next();
String[] temp = text.split(" ");
String name = temp[0];
String phoneNoTemp = temp[1];
System.out.println(name + ": name");
System.out.println(phoneNoTemp + ": phoneNoTemp");
我尝试过的输入是:
Input the name and phone no:
kate 99912222
旁注:是的,我确实导入了扫描仪
答案 0 :(得分:0)
请尝试使用s.nextLine()
而不是s.next()
,因为next()
方法只会消耗下一个分隔符,该分隔符默认为空白。