这是一个求一个数组里面的质数代码,但是我总是不能把数组的最后一个数字处理,把那两个FOR循环的参数调来调去,老是出现"数组越界"的提示.请高人帮帮忙,看看怎样解决这个问题?class BvP{
static int[] a={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
static int j=0;
public static int [] BdP(int[] b){
for(int i=0;i<a.length;i++){
for(j=i+1;j<a.length-1;j++){
if(a[j]==0){
j=j+1;
}
if(a[i]==0){
i=i+1;
}else if(a[j]%a[i]==0){
a[j]=0;
}
}
System.out.print(a[i]+" ");
}
return b;
}
public static void main(String[] args){
BdP(a);
}
}谢谢!
static int[] a={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
static int j=0;
public static int [] BdP(int[] b){
for(int i=0;i<a.length;i++){
for(j=i+1;j<a.length-1;j++){
if(a[j]==0){
j=j+1;
}
if(a[i]==0){
i=i+1;
}else if(a[j]%a[i]==0){
a[j]=0;
}
}
System.out.print(a[i]+" ");
}
return b;
}
public static void main(String[] args){
BdP(a);
}
}谢谢!
i=i+1;
你后边又来了一个
a[i]假设i=a.length-1;这时候是正确的,循环还在执行
然后是i=i+1;
这时候i=a.length
你再去访问a[i]这样就会报越界了
class BvP{
static int[] a={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
static int j=0;
public static int [] BdP(int[] b){
for(int i=0;i <a.length;i++){
for(j=2;j <a[i];j++){
if(a[i]%j==0){
a[i]=0;
}
}
System.out.print(a[i]+" ");
}
return b;
}
public static void main(String[] args){
BdP(a);
}
}
谢谢回复,但是我还是不是很明白你的解析,我不知道你说的是哪一行,还有,为什么i=a.length时
访问a[i]这样就会报越界呢?i=a.length时,i不是等于19吗?a[19]不是等于20吗?
static int[] a = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; static int j = 0; public static int[] BdP(int[] b) {
for (int i = 0; i < a.length; i++) { for (j = i + 1; j < a.length; j++) { if (a[j] == 0 && j < a.length-1) {
j = j + 1;
}
if (a[i] == 0) {
i = i + 1;
} else if (a[j] % a[i] == 0) {
a[j] = 0;
}
}
if(a[i]!=0){
System.out.print(a[i] + " ");
}
}
return b;
} public static void main(String[] args) {
BdP(a);
}
}
static int[] a={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
static int j=0;
public static int [] BdP(int[] b){
for(int i=0;i <a.length;i++){
for(j=2;j <a[i];j++){
if(a[i]%j==0){
break;
}
}
if(j>=a[i])
System.out.print(a[i]+" ");
}
return b;
}
public static void main(String[] args){
BdP(a);
}
}
a[20]不是错了吗?
.....
if(a[i]==0){
i=i+1; }
...
里面加1?
就可以把20计算进去呢?
谢谢