-2

This code is meant to find the 1001st prime number:

public class problem7 {

  public static void main(String[] args) {
    int[] myarray = new int[1001];
    int j = 0;
    boolean prime = false;

    for(int i = 2;;i++){
        for(int k = 2;k <i; k++){
            if(i== (k-1) && i % k != 0){
                prime = true;
            }

            if (i % k == 0){
                prime = false;
                prime = true;
            }
            if (prime){
                myarray[j] = i;
            }
            if(j==1000){
                System.out.println(myarray[1000]);
            }
            j++;
        }
    }
  }
}

It tells me my array is out of bounds. Not sure why. Any help would be appreciated

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276

2 Answers2

0

To fix this particular problem, you have to stop your code once you have found the number you want (by returning after printing the value you found):

if(j==1000){
    System.out.println(myarray[1000]);
    return;
}

This will avoid the next call of j++;, and the ArrayIndexOutOfBoundsException the next time you call myarray[j] = i;.

Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
0

after doing

        if(j==1000){ //if j is 1000
            System.out.println(myarray[1000]);
        }
        j++; // now j is 1001

you are not stopping your execution. In the next iteration, you are trying to do

        if (prime){
            myarray[j] = i; // your j is 10001
        }

So either break from the both loops or return once you print myarray[1000].

Karthik
  • 4,950
  • 6
  • 35
  • 65