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

后端 未结 5 1426
孤独总比滥情好
孤独总比滥情好 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条回答
  •  萌比男神i
    2021-01-15 15:19

    By creating array arr[] = {j}, you have created an array which contains simply j, or 1. That means the length of the array is 1, because it contains 1 element. Thus, arr[1] is out of bounds. Java does not dynamically resize arrays, so you must create a sufficiently large array to contain all of the data you plan to hold. Either that or use something like an ArrayList, which is dynamically resizeable.

提交回复
热议问题