Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Array Index Out of Bounds Exception

Tags:

java

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.

like image 310
Arly Avatar asked Oct 16 '10 23:10

Arly


1 Answers

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.

like image 143
codaddict Avatar answered Sep 22 '22 13:09

codaddict