-1

I'm attempting to write a method that will take in a String array of elements, a 2D double array of sample values, and an element to search. It will search for and return the sample number that contains the highest amount of that element. It's throwing me an Array Index Out of Bounds Exception (Index 6 out of bounds for length 6), and I can't figure out the reason. Below is the code I have so far.

public static int searchHighestSample(double[][] samples, String[] elements, String element){
    int elementSearch = 0;
    for(String elm : elements){
        if(elm.toLowerCase().compareTo(element.toLowerCase()) == 0){
            break;
        }
        elementSearch++;
    }
    int sampIndex = 0;
    double highest = 0;
    int i = 1;
    for(double[] data : samples){
        if(data[elementSearch] > highest){
            highest = data[elementSearch];
            sampIndex = i;
        }
        i++;
    }
    return sampIndex;
}

1 Answers1

1

Array indexes start at 0, so for an array of length 6 the indexes range from 0-5. The problem in your code is that elementSearch has a max value of elements.length - 1, while data.length - 1 can be lower than this (and obviously is, otherwise you wouldn't get the error).

Software Engineer
  • 15,457
  • 7
  • 74
  • 102