0

I'm trying to get all prime numbers between 1 and 10 and then putting them into an array. I get the ArrayIndexOutOfBoundsException error.

Am I getting this because the first for loop has starNum <=10 and the array technically doesn't have any values yet?

I am not sure how else to phrase the statement while still have the range 1 through 10. Help is greatly appreciated.

public static void main(String[] args) {

    int [] array = new int[args.length];

    for (int starNum = 1; starNum <= 10; starNum ++){
        boolean isPrime = true;
        int list = Integer.parseInt(args[starNum]);

        for (int i = 1; i*i <= starNum; i++) {
            if (starNum % 2 == 0) {
                isPrime = false;
            }
        }
        if (isPrime) {
            System.out.println(starNum);
            array[starNum] = list;
            System.out.println(array);
        }
    }
}
Samuel Kok
  • 585
  • 8
  • 16
Hernan Razo
  • 59
  • 12

2 Answers2

0

Make sure that Array Index starts from 0 and last element index is length -1.

Simple program to find prime number between two ranges i.e. in your case (1 to 10) -

public static void main(String[] args) {
    int i, flag;
    int low = 0;
    int high = 10;
    int arr[] = new int[10];
    int index = 0;
    while (low < high) {
        flag = 0;

        for (i = 2; i <= low / 2; ++i) {
            if (low % i == 0) {
                flag = 1;
                break;
            }
        }

        if (flag == 0) {
            arr[index] = low;//prime number array, print it to check
            index++;
        }
        ++low;
    }
}

arr is the array which contains prime numbers. you can provide minimum value to low and maximum value to high.

ketan
  • 2,732
  • 11
  • 34
  • 80
0

The first forloop has the issues.

Index will always start with 0(zero) but not with 1. So change your first for loop like below

for (int starNum = 0; starNum < args.length && starNum <= 10; starNum ++){
Ravi MCA
  • 2,491
  • 4
  • 20
  • 30