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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With