java.lang.ArrayIndexOutOfBoundsException查找素数并使用它创建数组时发生异常
目标-找到所有素数并用它创建数组 做了什么- 已创建的方法primeReturner-如果数为prime,则返回true-java.lang.ArrayIndexOutOfBoundsException查找素数并使用它创建数组时发生异常,java,arrays,exception,loops,indexoutofboundsexception,Java,Arrays,Exception,Loops,Indexoutofboundsexception,目标-找到所有素数并用它创建数组 做了什么- 已创建的方法primeReturner-如果数为prime,则返回true- private static boolean primeReturner (int i){ for (int j=2;j<i; j++){ if (i%j==0) return false; } return true; } 结果,所有素数数组都成功创建 但是在打印这个数组的过程中,我得到了ja
private static boolean primeReturner (int i){
for (int j=2;j<i; j++){
if (i%j==0)
return false;
}
return true;
}
结果,所有素数数组都成功创建
但是在打印这个数组的过程中,我得到了java.lang.ArrayIndexOutOfBoundsException错误
如何解决此错误?在
if(primeReturner(i))==true)
块中执行i++
。这是对for
循环i++
的的补充。您很可能会得到一个ArrayIndexOutOfBoundsException
,因为i
索引将达到大于100的值,这是您的数组最大大小。删除if
块中的i++
。错误是由于使用相同的变量在数组中建立索引(即第n个素数的索引)和素数的值造成的。因此,如果索引为非素数,则在simpleArray
中构造的数组将具有零值;如果索引为素数,则在i
中构造的数组将具有零值。如果需要完全压缩的数组,则需要第二个索引:
private static void simpleArray() {
int []a = new int [100];
a[0] = 2; // by definition 1 is not prime
int i = 1;
int possible_prime = 3;
while (i < a.length) {
if (primeReturner(possible_prime)) {
a[i++]=possible_prime;
}
possible_prime++;
}
}
private static void simpleArray(){
int[]a=新的int[100];
[0]=2;//根据定义,1不是素数
int i=1;
int可能的_素数=3;
while(i
有关1的素性的讨论,请参见。(int i=2;i查找错误-需要通过添加限制来停止循环
最后的代码是
private static void simpleArray() {
int []a = new int [100];
a[0]=1;
a[1]=2;
int count=2;
while (count<100){
for (int i=3;**i<524** ; ++i){
if (primeReturner(i)==true){
a[count]=i;
count++;
}
}
}
for (count=0; count<a.length; count++){
System.out.print(" " + a[count]);
}
}
private static void simpleArray(){
int[]a=新的int[100];
a[0]=1;
a[1]=2;
整数计数=2;
while(count)在运行一些java.lang.ArrayIndexOutOfBoundsCeption期间,我没有任何异常。您能用main
方法发布完整的代码吗?在您提供的代码中,在访问数组的所有地方,都保证索引低于数组长度。优化。建议:在primeReturner(int i)中
您可以改进循环:intupperbound=Math.sqrt(i);for(intj=2;j
public static void main (String[]args) throws IOException{
System.out.println("Menu:");
....
System.out.println("Array with simple numbers - enter 7");
select = getNumber ();
switch (select){
.....
case 7:{
simpleArray();
}
}
}
private static void simpleArray() {
int []a = new int [100];
a[0] = 2; // by definition 1 is not prime
int i = 1;
int possible_prime = 3;
while (i < a.length) {
if (primeReturner(possible_prime)) {
a[i++]=possible_prime;
}
possible_prime++;
}
}
for (int i=2; i<a.length; i++){
if (primeReturner(i)==true){
a[i]=i;
i++;
}
}
for (int i=2; i<a.length; i++){
if (primeReturner(i)==true){
a[i]=i;
}
}
private static void simpleArray() {
int []a = new int [100];
a[0]=1;
a[1]=2;
int count=2;
while (count<100){
for (int i=3;**i<524** ; ++i){
if (primeReturner(i)==true){
a[count]=i;
count++;
}
}
}
for (count=0; count<a.length; count++){
System.out.print(" " + a[count]);
}
}