简体   繁体   English

当我尝试对来自控制台 (Java) 的输入进行标记时,为什么会收到 ArrayIndexOutOfBoundsException?

[英]Why am I getting an ArrayIndexOutOfBoundsException when I try to tokenize the input from the console (Java)?

I'm trying to separate the input from the console using the split method, and then putting each of these values into separate containers, and I keep on getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 .我正在尝试使用 split 方法将输入与控制台分开,然后将这些值中的每一个放入单独的容器中,并且我不断收到此错误: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 I assume the issue is that it ignores the input after the first space, but I am clueless as to why and how to solve that.我认为问题在于它忽略了第一个空格之后的输入,但我不知道为什么以及如何解决这个问题。

Could someone tell me what I'm doing wrong and advise what I should do so that the text after the space is stored in my container?有人可以告诉我我做错了什么并建议我应该怎么做才能将空间之后的文本存储在我的容器中吗? Thank you in advance.先感谢您。

    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");

The input I tried it with was:我尝试过的输入是:

Input the name and phone no: 
kate 99912222

Sidenote: Yes, I did import the scanner旁注:是的,我确实导入了扫描仪

Try to use s.nextLine() instead of s.next() because the next() method only consumes until the next delimiter, which defaults to any whitespace.尝试使用s.nextLine()而不是s.next()因为next()方法只消耗直到下一个分隔符,默认为任何空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM