How can I re-assign values in a one-dimensional array?

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?

2 answers

  • answered 2018-10-22 22:23 Ben P.

    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.

  • answered 2018-10-22 22:25 Johan

    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.