-1

I'm trying to make a helper method that starts at a number, startLook, inclusive, and returns the next num number of primes from that number. Here is my code:

public int[] nPrimes(int num, int startLook) {
    int y = startLook;
    int x = 2;
    int[] c = new int[num];
    int d = 0;
    while (x <= y/2) {
        if (y % x == 0) {
            x++;
            continue;
        }
        if (y % x != 0) {
            c[d]=y;
            d++;
        }
        x++;
    }
    return c;
}

This results in ArrayIndexOutOfBoundsException and not registering primes. What am I doing wrong? Thanks in advance.

Christian Hujer
  • 17,035
  • 5
  • 40
  • 47

1 Answers1

0

You're getting ArrayIndexOutOfBoundsException error because in your second if statement d is incremented and you never check if it reached num-1 (last possible index for your c array).

You should consider changing your while loop condition to something checking d value.