ArrayIndexOutOfBoundsException有时,其他时候的代码运行得很好吗?

时间:2019-06-03 19:54:56

标签: java indexoutofboundsexception

我正在尝试测试Arduino音频可视化器,但是当我运行Java可视化器10次中有9次时,我得到了ArrayIndexOutOfBoundsException,而其他时候它运行良好。 ArrayIndexOutOfBoundsException:数字每次在0到32之间更改。

我考虑为ArrayIndexOutOfBoundsException添加第二条catch语句,但是感觉像是在解决更大的问题上使用创可贴。

void draw()
{
  String tempC = myPort.readStringUntil('\n');
  if (tempC != null)
  {  
  String[] items = tempC.replaceAll("\\[", "").replaceAll("\\]", 
"").replaceAll("\\s", "").split(",");

  int[] data = new int[32];

  for (int i = 0; i < 32; i++)
      {
        try {
            data[i] = Integer.parseInt(items[i]);
             } 
        catch (NumberFormatException nfe) {};
       }
    background(123);
  rect (20,300,10,-(data[0]));
  rect (40,300,10,-(data[1]));
  rect (60,300,10,-(data[2]));

此代码应从串行端口输入一个字符串(始终包含32个数字),如下所示: 160,0,0,0,0,0,0,10,0,10,0,10,0,0,0,0,0,0,0,0,0,0,0,10,10,0, 0,0,0,0,0,10,10 并将该字符串转换成一个数组,该数组称为大小为32(data [32])的数据,其中数组中的每个项目都是以“,”分隔的数字之一。然后,代码将创建高度等于数据大小的矩形。当我运行此代码时,我收到错误消息 ArrayIndexOutOfBoundsException:然后是0到32之间的某个数字。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的item数组并不总是具有32个值,这就是它有时会引发错误而有时不会引发错误的原因。最好的方法是将data初始化为确切的items长度,然后根据items数组中的元素数进行循环。

int[] data = new int[items.length];

for (int i = 0; i < items.length ; i++){
   try {
       data[i] = Integer.parseInt(items[i]);
   } 
   catch (NumberFormatException nfe) {};
}