destroted
destroted

Reputation: 51

Array indexing issues

I am trying to use a for loop to create 7 instances of a class. I can go through the loop 7 times, but once I press enter I get an ArrayIndexOutOfBound error.

My code is as follows:

Data[] temperatures = new Data[7];


for(int i=1; i<=temperatures.length + 1; i++)
{
    System.out.println("Please enter the temperature for day " + i);
    temperatures[i] = new Data(input.nextDouble());
}

Upvotes: 0

Views: 69

Answers (5)

piksu
piksu

Reputation: 16

Java array indexes

Array indexes start at 0. The problem with your code is that you are trying to access the 8th array element which doesn't exist. For more information, refer The Java™ Tutorials - Arrays.

Your code should look something like this:

Data[] temperatures = new Data[7]; // Indexes 0-6 (makes a total of 7 indexes)

// Start the loop from index 0, end it to index 6 (= temperatures.lenght)
for (int i = 0; i < temperatures.length; i++) {
    // Since it would sound strange to enter a temperature for day 0, notice (i+1)
    System.out.println("Please enter the temperature for day " + (i+1));
    temperatures[i] = new Data(input.nextDouble());
}

Upvotes: 0

Aniket Kulkarni
Aniket Kulkarni

Reputation: 12983

That is because array index starts with 0, and it must not be greater than the array size. In your case it starts from 1 to 8 and you array size is 7.

for(int i=0; i<temperatures.length; i++)
{
  System.out.println("Please enter the temperature for day " + (i+1));
  temperatures[i] = new Data(input.nextDouble());
}

ArrayIndexOutOfBoundsException

public class ArrayIndexOutOfBoundsException
   extends IndexOutOfBoundsException

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Upvotes: 2

Nishant Modi
Nishant Modi

Reputation: 679

Arrays have index starting from 0 . IN your case indices would be 0 to 6 Solution : 1. Change Loop to for(int i=0; i

Upvotes: 0

SamDJava
SamDJava

Reputation: 267

This line is causing the error.

for(int i=1; i<=temperatures.length + 1; i++)

Your i in the loop should start from 0 as arrays in Java start from the 0th index.. Also your loop should go till i

This will navigate smoothly for 7 times. Try this

for(int i=0; i < temperatures.length; i++)

Upvotes: 1

Ren&#233; Link
Ren&#233; Link

Reputation: 51353

Array indexes start at 0. Therefore you must loop this way

 for(int i=0; i < temperatures.length; i++)

Upvotes: 3

Related Questions