Reputation: 439
I am trying to create a array with Java that can hold as many numbers as the index 'i' is big.
for (int i = 0; i <= 10; i++)
{
int[] zahlenListe = new int[i];
zahlenListe[i] = i + 5;
System.out.println(zahlenListe[i]);
}
but I am always getting the error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Start.main(Start.java:27)
Java:27 is this line of code: zahlenListe[i] = i + 5;.
But everything is working fine when I change this line
int[] zahlenListe = new int[i];
to this:
int[] zahlenListe = new int[11];
Anybody cares to explain where the error is?
Upvotes: 1
Views: 1254
Reputation: 1398
Basically because in your condition you are telling the computer to go to the 11th element. Think of it this way ...
int i = 0;
First iteration i = 0
if i <= 10; then i = i + 1
Second iteration i = 1
if i <= 10; then i = i + 1
Third iteration i = 2
if i <= 10; then i = i + 1
Fourth iteration i = 3
if i <= 10; then i = i + 1
Fifth iteration i = 4
if i <= 10; then i = i + 1
Sixth iteration i = 5
if i <= 10; then i = i + 1
Seventh iteration i = 6
if i <= 10; then i = i + 1
Eighth iteration i = 7
if i <= 10; then i = i + 1
Ninth iteration i = 8
if i <= 10; then i = i + 1
Tenth iteration i = 9
if i <= 10; then i = i + 1
Eleventh iteration i = 10
if i <= 10; then i = i + 1
Once you get here you are trying to access an element that does not exist. Because your condition says that as long as i is less that or equal that 10, it should repeat the task. If you change <= for < then you stop at the last element available.
Upvotes: -1
Reputation: 4347
You need to start 0
to size-1
in an array as you see;
int[] zahlenListe = new int[i];
Your array size is always i
which means you can allowed to access max i-1
Assuming that i
always bigger than 0
Upvotes: 1
Reputation: 3103
If you creating an array using:
int[] zahlenListe = new int[i];
The last element in array zahlenListe would be zahlenListe[i-1] instead of zahlenListe[i]. In addition, assuming i should start with 1 instead of 0 because an array of length is pointless.
Therefore, use
zahlenListe[i-1] = i + 5;
System.out.println(zahlenListe[i-1]);
Upvotes: 1
Reputation: 121998
Array indices are zero based. Hence the maximum index for i
sized array is i-1
.
Upvotes: 8
Reputation: 262534
int[] zahlenListe = new int[i];
zahlenListe[i] = i + 5;
Arrays start at index 0
.
So index i
will never be in an i
-dimensional array. It stops at i-1
.
For i == 0
the array is empty (no entries at all).
You may want to start your loop at i=1
.
From your code it is also not clear why you need an array at all (but you probably have more code in there that you are not showing).
Upvotes: 1
Reputation: 393846
An array of length i
doesn't have an i
'th index. The valid indices go from 0
to i-1
.
If you initialize your array with int[] zahlenListe = new int[i+1];
, you'll be able to assign a value to zahlenListe[i]
.
Upvotes: 5