【问题标题】:ArrayIndexOutOfBoundsException, but the elements print fineArrayIndexOutOfBoundsException,但元素打印正常
【发布时间】:2015-10-16 11:30:13
【问题描述】:

这个错误信息是什么意思:

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 at Program.main(Program.java:123)

这是第 123 行:

System.out.println(tempHolder[1]);

所以说没有数组元素 1?但是,这是一个循环,并且该位置的所有 100 个元素都打印得很好。代码如下:

数组splitResult 有100 个元素。

    int counter = 0;
    for (String s: splitResult){ 
      counter++; 
      counterForRegex = String.valueOf(counter);  
      stringRegex = "(\\s*)?" + counterForRegex + "(\\s*)?"; 
      patternCounter = Pattern.compile(stringRegex); 
      tempHolder = patternCounter.split(s, 2);  // This takes each of the 100 elements and separates it into 0) before the number, and 1) after the number, putting each element in array tempHolder.
      splitResult[counter-1] = tempHolder[0]; 
      System.out.println(tempHolder[1]); // These all print fine.
    }

【问题讨论】:

  • 对您的代码进行适当的调试。
  • 打印 splitResult 的大小以验证它有 100 个元素以及每次迭代的 tempHolder 的大小,看看是否总是 >= 2。
  • splitResult 中的一个字符串不包含数字序列;因此 tempHolder.length == 1 和 tempHolder[0] 包含所有该字符串。
  • 也许你应该先测试一下if (!s.matches(".*" + stringRegex + ".*")) // will not split

标签: java regex split


【解决方案1】:

tempHolder = patternCounter.split(s, 2);//当没有找到数字时,拆分结果只返回输入。

tempHolder.length 将为 1,在这种情况下,尝试访问 tempHolder[1] 时会抛出 java.lang.ArrayIndexOutOfBoundsException。

 tempHolder = patternCounter.split(s, 2); 
  if(tempHolder.length>=2){//check the length of tempHolder
     splitResult[counter-1] = tempHolder[0]; 
     System.out.println(tempHolder[1]); // These all print fine.
  }

【讨论】:

    猜你喜欢
    • 2014-03-16
    • 1970-01-01
    • 2020-09-29
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    相关资源
    最近更新 更多