首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

~数3退1 循环数组实现运行出错,提示数组越界

2014-01-12 
求助~数3退1 循环数组实现运行出错,提示数组越界public class Count3Quit3{public static void main(Strin

求助~数3退1 循环数组实现运行出错,提示数组越界
public class Count3Quit3{
public static void main(String[] args){
int[] arr = new int[500];
for(int i=0;i<arr.length-1;i++){
arr[i] = i+1;
}
arr[arr.length-1] = 0;
int count = arr.length;
int countNum = 0;
int index = 0;
while(count>1){
countNum++;
if(countNum == 3){
countNum = 0;
arr[index-1] = arr[index];
count--;
}
index = arr[index];
}
//System.out.println(index);
}
}

~数3退1 循环数组实现运行出错,提示数组越界
你的 arr[arr.length-1] = 0; 说明499下标的为0啊
然后你后面又arr[index-1] 出现了arr[-1]所以就报错了
[解决办法]
因为前面有代码

引用
arr[arr.length-1] = 0;


而当index等于499时,arr[499]的值为0,这时index的值为0
引用
index = arr[index];


引用
arr[index-1] = arr[index];

进入这里时,index=0会出现arr[-1] = arr[0],所以报错了
[解决办法]
首先用数组来实现这样做实在不太明智,因为数组的长度是固定的,而每去掉一个,数组的“长度”就要减一,最后直到只剩下一个为止。所以必须有一个“指针”指向最末尾的位置,每去掉一个这个指针就往前移一位。
/**
 * 翻牌-丢牌游戏,将一叠牌拿在手里,把最上面的牌翻到最下面,每翻若干次就
 * 丢掉一张最上面的牌,直到剩下最后一张牌。
 */
public class CountAndDelete {

    public static final int ARRAY_SIZE = 500;         // 初始牌数

    public static final int MOVE_DISTANCE = 3;      // 每次翻牌的数量

    public static void main(String[] args) {
        int finalElement = countAndDelete(ARRAY_SIZE, MOVE_DISTANCE);
        System.out.println("Final element: " + finalElement);
    }

    private static int countAndDelete(int arraySize, int moveDistance) {
        int[] arr = new int[arraySize];
        fillArray(arr);

        int bound = arraySize - 1;  // 最后剩余元素的位置
        int counter = 0;            // 总是指向最上面的牌

        while (bound > 0) {
            counter = moveCounter(counter, moveDistance, bound);
            deleteElement(arr, counter, bound);
            bound--;
        }

        return arr[0];
    }

    // 删除当前位置的数组元素,将后面的元素往前移
    private static void deleteElement(int[] arr, int position, int bound) {
        System.out.println("Delete: " + arr[position]);


        System.arraycopy(arr, position + 1, arr, position, bound - position);
    }

    // 往后数若干个位置
    private static int moveCounter(int currentPosition, int move, int bound) {
        return (currentPosition + move) % (bound + 1);
    }

    private static void fillArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }
    }
}


[解决办法]
通过boolean类型的数据,先把所有数组赋值为true,当数到三个的时候把值改为false,经过多次循环就可以得到最后一个为true,输出下标
public class Count3Quit1 {
public static void main(String args[]){
boolean[] arr = new boolean[500];
for(int i=0; i<arr.length; i++){
arr[i] = true;
}

int leftcount = arr.length;
int countnum = 0;
int index = 0;

while(leftcount>1){
if(arr[index] == true){
countnum++;
if(countnum == 3){
countnum = 0;
arr[index] = false;
leftcount--;
}
}
index++;

if(index==arr.length){
index=0;
}
}

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

热点排行