Java: Array Index Out of Bounds Exception
System.out.print("Enter an integer: ");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int lArray = x - 2;
int[] newArray = new int[lArray];
System.out.println("Let's display all possible integers...");
for (int i = 0; i <= newArray.length; i++) {
newArray[i] = i + 2;
System.out.print(newArray[i] + " ");
}
I've just started Java recently, but I sure that if I coded similarly in another language, I would face the same problem. This is an excerpt from an application where it lists all the prime numbers up until the user's input.
The reason why x-2 is used as the definition of lArray is because the length of the array will be all the integers from 2 until the number {2, 3, 4, 5... x}.
I noticed that for the line
for (int i = 0; i <= newArray.length; i++) {
if I change i <= newArray
to i < newArray
, the code works without error. However, the user's input, x, is left out which is a problem if x is prime.
You should use <
and not <=
in:
for (int i = 0; i <= newArray.length; i++)
^^
If foo
any array, valid index of foo
are [0,foo.length-1]
Using foo.length
as an index will cause ArrayIndexOutofBoundsException
.
And also lArray
which contains number of natural numbers <=x
but excluding only one number 1
, its value should be x-1
and not x-2
.
Change the array length to (x - 1)
instead, and go with the <
condition, which you've already found is necessary to avoid the out-of-bounds exception.
The reason you need an array that is 1 element larger than what you're currently using is because there are (n - 1)
candidates that must be considered between 2 and n , not (n - 2)
.
For example, there are two candidates less than or equal to three (2 and 3), both of which, coincidentally, happen to be prime.