Java: Array Index Out of Bounds Exception

这一生的挚爱 提交于 2019-12-17 07:52:34

问题


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.


回答1:


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.




回答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.




回答3:


for (int i = 0; i <= newArray.length; i++) //should be <, not <=
for (int i = 0; i < newArray.length; i++)



回答4:


You need to use:

int lArray = x - 1;

And change your condition to use < instead of <=.

In Java as in C/C++, arrays are ZERO based. So your array of N values will go from index 0 to N-1.

Taking your example: {2, 3, 4, 5... x}.

You will need N-1 values to store all positive numbers but 1 in an integer array. So, if N equals to 4, your array will be:

newArray[0] = 2;
newArray[1] = 3;
newArray[2] = 4;

Hence, array lenght must be 3 (N-1).



来源:https://stackoverflow.com/questions/3951252/java-array-index-out-of-bounds-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!