1

I'm calculating the max height that is inserted in the applications, and it gives me a ArrayIndexOutOfBound error, the time of values inserted is the same of the length of the array including the 0 index, but i am still having this error.

int nrPersons = 3;
double[] height = new double[nrPersons];
double maxHeig = 0;

for (int i = 0; i <= nrPersons; i++) {
    Scanner in = new Scanner(System.in);
    in.useLocale(Locale.US);

    System.out.println("Insert Height");

    height[i] = in.nextDouble();

    if (height[i]> maxHeig)
        maxHeig = height[i];

}

System.out.println("The max Height is: "+maxHeig);
Dmitry
  • 13,797
  • 6
  • 32
  • 48
Pedro
  • 1,459
  • 6
  • 22
  • 40

1 Answers1

3

Your problem is here

for (int i = 0; i <= nrPersons;i++){

You need to not have i ever reach the value of nrPersons as this will be out of bounds. Arrays in Java are indexed from 0 and have the number of elements defined. So for some array:

int[] i = new int[3];
i[0] = 0; //fine
i[1] = 0; //fine
i[2] = 0; //fine
i[3] = 0; //**ERROR** Out of bounds

Simple solution is to use this common syntax:

for (int i = 0; i < nrPersons; i++)
Kon
  • 10,702
  • 6
  • 41
  • 58