ArrayIndexOutOfBoundsException 有时,有时代码运行完美?

ArrayIndexOutOfBoundsException sometimes, other-times code runs perfectly?

我正在尝试测试 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,10,10,0, 0,0,0,0,0,10,10 并将该字符串转换为一个名为 data of size 32 (data[32]) 的数组,其中数组中的每一项都是由“,”分隔的数字之一。然后代码将创建高度等于数据大小的矩形。当我 运行 此代码时,我收到错误消息 ArrayIndexOutOfBoundsException: 然后是 0 - 32 内的某个数字。 非常感谢任何帮助。

您的 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) {};
}