日期:2014-05-20  浏览次数:20763 次

数三退一程序的报错 请各位指点~谢谢了
package com.test2;
//数三退一
public class Count3Quit {
public static void main(String[] args){
boolean[] a=new boolean[500];
for(int i=0;i<a.length;i++){a[i]=true;}
int index;
int count=0;
int len=a.length;
for(index=0;len>=1;index++){
if(a[index]==true){
count++;
if(count==3){count=0;a[index]=false;len--;}
}
if(index==a.length){index=0;}
}

for(int i=0;i<a.length;i++){
if(a[i]==true){System.out.print(i+1);}
}
}
}


报错:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 500
at com.test2.Count3Quit.main(Count3Quit.java:16)

我想问的是:这种for循环结束条件这样写:for(index=0;len>=1;index++)可以么?报错显示数组越界 ,我不太明白是哪里的问题 新人 还请各位多多指点不胜感激~

------解决方案--------------------
少年,数组下标是从0开始的。定义一个500大的数组下标为0-499,
你的代码肯定会一直循环到a.length,就是500,a[500]已经越界了。
------解决方案--------------------
上面有点问题


public class Count3Quit {
public static void main(String[] args) {
boolean[] a = new boolean[500];
for (int i = 0; i < a.length; i++) {
a[i] = true;
}
int index;
int count = 0;
int len = a.length;
for (index = 0; len > 1; index++) {
if (a[index] == true) {
count++;
if (count == 3) {
count = 0;
a[index] = false;
len--;
}
}
if (index == a.length - 1) {
index = -1;
}
}

for (int i = 0; i < a.length; i++) {
if (a[i] == true) {
System.out.print(i + 1);
}
}
}
}