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

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

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

Comments

1

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.