Why do I get an ArrayIndexOutOfBoundsException in this prime number check?

后端 未结 5 1381
孤独总比滥情好
孤独总比滥情好 2021-01-15 14:40

I was finding out highest prime factor which divides num, as shown in program, there\'s a issue with array and

arr[j] = i;
j++;
Excepti         


        
5条回答
  •  北海茫月
    2021-01-15 15:24

    Looks like you start j = 1 and your array only has one element in it to begin, so on the first pass through your for loop you look for arr[1], but the first element in an array is at arr[0]. Java arrays are zero indexed meaning if you have 10 elements in the array they are located in arr[0] to arr[9].

提交回复
热议问题