0

My question is two-fold.

I have an array:

double [] temperature = {60.9, 62.6, 67.4, 71.5, 77.1, 81.2, 82.4, 82.5, 81.1, 75.3, 68.8, 63.0};

When I try to convert these Fahrenheit values to Celsius or Kelvin using:

for(int index = 0; index <= temperature.length; index++) {
    temperature[index] = temperature[index] * tempConverter;
    averageTemp += temperature[index];
}

I get an ArrayIndexOutOfBoundsException on temperature[index = temperature[index] * tempConverter;

  1. Why do I get this error?
  2. How do I fix this and reassign my values?
  • 1
    In the `for`-loop condition it must be `index < temperature.length`. Otherwise the loop is executed with `index = temperature.length` which is out of bounds. – Michael Butscher Oct 22 '18 at 22:22
  • 1
    https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – jmj Oct 22 '18 at 22:23

2 Answers2

1

Change your for loop to use < instead of <=:

for(int index = 0; index < temperature.length; index++)

Consider an array with one element. That would make array.length equal to 1, and if you used <= you would inspect both array[0] and array[1]... but you know there's only one element. That's why you use < instead.

Ben P.
  • 52,661
  • 6
  • 95
  • 123
0

An array of length n which starts on index 0 will have its last index at n-1.

At the moment your loop will go from 0 to n inclusive (<= n), which will make it out of bounds from the reserved space when it reaches index n. Instead you need to go from 0 to n exclusive (< n), like this:

for(int index = 0; index < temperature.length; index++) {
    ...
}

Think of the array of length 3 with the elements representing their own indexes:

a = [0, 1, 2]

Trying to access the element at index = array length (3) will not work because there is no element at index 3 in the array.

Johan
  • 3,577
  • 1
  • 14
  • 28