Search code examples
javaindexoutofboundsexception

ArrayIndexOutOfBoundsException sometimes, other-times code runs perfectly?


I am trying to test an Arduino audio visualizer but when I run the Java visualizer 9 times out of 10 I get an ArrayIndexOutOfBoundsException and other times it works perfectly. The ArrayIndexOutOfBoundsException: number changes each time between 0 and 32.

I looked into including a second catch statement for ArrayIndexOutOfBoundsException but that felt like putting a bandaid over a bigger problem.

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]));

This code should take in a string (which will always contain 32 numbers) from the serial port which looks like this: 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 and turn that string into an array called data of size 32 (data[32]) where each item in the array is one of the numbers separated by a ",". Then the code will create rectangles of a height equal to the magnitude of the data. When I run this code I get the error message ArrayIndexOutOfBoundsException: and then some number within 0 - 32. Any help is greatly appreciated.


Solution

  • Your item array doesn't always have 32 values, which is the reason it sometimes throws an error and sometimes doesn't. The best way would be to initialize data to exact length of items, then loop based on the number of elements in the items array.

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