Reputation: 433
When writing something simple like this:
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter array size: ");
int x = sc.nextInt();
int [] anArray;
int index = 100;
anArray = new int[x];
for (int i=0; i<=x; i++){
anArray[i] = index;
index += 100;
System.out.println ("Element at index "+ i + ": " + anArray[i]);
}
}
}
Netbeans compiles and runs the code properly but the output ends up looking like this:
run:
Please enter array size:
12
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Element at index 10: 1100
Element at index 11: 1200
at Practice.main(Practice.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
Which seems off to me.. why is the exception thrown halfway through the code? and then finished at the end?
And it points to line 21: anArray[i] = index;
Honestly not a big issue.. i'm just playing around and reviewing some basics of Java (it's been a while...) and the exception is making me feel like I'm doing something wrong but then I'm not sure I actually am because it seems to be working how I intended.
Thank you!
Upvotes: 0
Views: 73
Reputation: 34176
Change the for statement:
for (int i=0; i<x; i++){ // Change <= to <
anArray[i] = index;
index += 100;
System.out.println ("Element at index "+ i + ": " + anArray[i]);
}
If you create an array with length = 12
, then you can access it by:
anArray[0]
anArray[1]
...
anArray[11]
But you are accessing it up to anArray[12]
, so it throws the error.
Upvotes: 2