为什么我在尝试对来自控制台 (Java) 的输入进行标记化时收到 ArrayIndexOutOfBoundsException?
Why am I getting an ArrayIndexOutOfBoundsException when I try to tokenize the input from the console (Java)?
我尝试使用 split 方法将输入与控制台分开,然后将这些值中的每一个放入单独的容器中,但我不断收到此错误:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
。我假设问题是它忽略了第一个 space 之后的输入,但我不知道为什么以及如何解决这个问题。
有人可以告诉我我做错了什么并建议我应该怎么做才能将 space 之后的文本存储在我的容器中吗?提前谢谢你。
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
旁注:是的,我确实导入了扫描仪
尝试使用 s.nextLine()
而不是 s.next()
,因为 next()
方法只消耗到下一个分隔符,默认为任何空格。
我尝试使用 split 方法将输入与控制台分开,然后将这些值中的每一个放入单独的容器中,但我不断收到此错误:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
。我假设问题是它忽略了第一个 space 之后的输入,但我不知道为什么以及如何解决这个问题。
有人可以告诉我我做错了什么并建议我应该怎么做才能将 space 之后的文本存储在我的容器中吗?提前谢谢你。
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
旁注:是的,我确实导入了扫描仪
尝试使用 s.nextLine()
而不是 s.next()
,因为 next()
方法只消耗到下一个分隔符,默认为任何空格。