我不断收到数组超出范围的错误,我无法弄清楚出了什么问题。
int[] oddArray = new int[500];//holds all the odd numbers
int[] primeArray = new int[500];//holds all the prime numbers
int[] modArray = new int[500];//holds all the mod values
int remainder, p = 0, x = 0;
//fills up the oddArray & modArray
for(int n = 0; n < 500; n++)
{
oddArray[n] = (n * 2) + 1;
modArray[n] = (n* 2) + 1;
}
for(int i = 0; i < 500; i++)
{
//finds prime numbers
for(int n = 0 ; n < 500; n++)
{
//divides the odd numbers by the current mod value
remainder = oddArray[n] % modArray[x];
//if remainder is not 0 it will place a value in prime array
if(remainder != 0)
{
primeArray[p] = oddArray[n];
p++;
}
}
//prints out list of odds/mod/and primes side by side
System.out.println(oddArray[i] + " | " + modArray[i] + " | " + primeArray[p]);
++x;
}
这是错误代码
1 | 1 | 0
3 | 3 | 0
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:500 at projectprime_v1.ProjectPrime_V1.main(ProjectPrime_V1.java:41) Java结果:1 建立成功(总时间:0秒)
答案 0 :(得分:1)
您永远不会重置p
,因此最终会超过499,并导致异常。确保在循环中写入p = 0;
以重置它。 x
希望这有帮助!