【问题标题】:Why am I getting an ArrayIndexOutOfBoundsException when I try to tokenize the input from the console (Java)?当我尝试对来自控制台 (Java) 的输入进行标记时,为什么会收到 ArrayIndexOutOfBoundsException?
【发布时间】:2020-10-29 05:30:11
【问题描述】:

我正在尝试使用 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

旁注:是的,我确实导入了扫描仪

【问题讨论】:

  • 扫描仪的下一个方法将只采用字符串的第一部分。如果字符串之间有空格,它将不会拾取第二部分,因此您会收到此错误

标签: java arrays exception delimiter tokenize


【解决方案1】:

尝试使用s.nextLine() 而不是s.next(),因为next() 方法只消耗直到下一个分隔符,默认为任何空格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 2012-03-05
    • 2015-12-13
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多