从array-java中删除元素

时间:2014-05-27 09:06:16

标签: java arrays

我尝试从java数组中删除一个元素并移动数组,更新总值和计数。 这是我写的代码段,它给了我错误的结果,我该如何解决?

public void remove(int index)
{
    if(index > count-1 || index <0)
        System.out.println("Incorrect index.");
    else{
        if(index ==1){
            total -= numbers[index];
            numbers = new int [0];
            count--;
        }else{
            total -= numbers[index];
            for(int i=index; i < count; i++)
                numbers[i] = numbers[i+1];
            count--;
        }

    } 
}

我用这个测试代码;

NumberList n10 = new NumberList(-5); 
n10.add(45); 
n10.remove(0);
System.out.println(n10); 
n10.add(12); 
n10.add(25); 
n10.add(20);
System.out.println(n10); 
n10.remove(1);
n10.remove(1);
n10.remove(0);
System.out.println(n10);

我得到了

Size of the array must be greater than 0. [Empty List] [12, 25, 20]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at NumberList.remove(NumberList.java:113)   
        at Prelab8.main(Prelab8.java:102)

1 个答案:

答案 0 :(得分:1)

您将在for循环中获得arrayindexoutofbound。 它应该是

   for(int i=index; i < count-1; i++)

最终代码示例:

public class Test {
static int count;
static int total;
static int [] numbers = {1,2,3,4};
    public static void main(String[] args) throws IOException {


        count = numbers.length;
        for (int i : numbers) {
            total = total+i;
        }
        remove(3);

        System.out.println(total);
        System.out.println(count);
    }
    public static void remove(int index)
    {
        if(index > count-1 || index <0)
            System.out.println("Incorrect index.");
        else{
            if(index ==1){
                total -= numbers[index];
                numbers = new int [0];
                count--;
            }else{
                total -= numbers[index];
                for(int i=index; i < count-1; i++)
                    numbers[i] = numbers[i+1];
                count--;
            }

        } 
    }
}
相关问题