繁体   English   中英

当我尝试对来自控制台 (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 我认为问题在于它忽略了第一个空格之后的输入,但我不知道为什么以及如何解决这个问题。

有人可以告诉我我做错了什么并建议我应该怎么做才能将空间之后的文本存储在我的容器中吗? 先感谢您。

    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()方法只消耗直到下一个分隔符,默认为任何空格。

暂无
暂无

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

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