0

In the method below, I'm trying to remove values in array input that are less than 0 and greater than 9. I've been doing research and I found that using Arraylist.remove() would probably be the best way but I am not familiar with that yet. So what I did is try to copy the whole array into a "garbage" array and only put values that are less than 0 and greater than 9. But my output still comes out to be 123145123145-110?

 public static void test (){
 int[] input = {1,2,3,1,4,5,1,2,3,1,4,5,-1,10};

    int[] garbage = new int[input.length];
    for (int i=0; i<input.length; i++){
        if (input[i] < 0 && input[i] > 9){
            garbage[i] = input[i];
        }
        int x = input[i];
        System.out.print(x);
  }

//EDIT

  public static void votes(){
     int[] input = {1,2,3,1,4,5,1,2,3,1,4,5,-1,10,20};
        int count = 0;
        int[] garbage = new int[input.length];
        for (int i=0; i<input.length; i++){
            if (input[i]<0){
                garbage[count] = input[i];
                i++;
                count++;
            }
        int x = input[i];
        System.out.print(x);

        }

  }
4

4 回答 4

0

好的,因为您在评论中说您真正想要做的是打印出元素 >0 和 <9,而不是实际更改数组,这变得非常简单。

public static void votes(){
    int[] input = {1,2,3,1,4,5,1,2,3,1,4,5,-1,10,20};
    for (int i=0; i<input.length; i++){
        if (input[i] >= 0 && input[i] <= 9){
            System.out.print(input[i]);
        }
    }
}

就是这样!

于 2013-07-31T23:11:49.997 回答
0

您使用了错误的间隔。

if (input[i] < 0 && input[i] > 9)

应该是这个

if (input[i] < 0 || input[i] > 9)

您的垃圾应该是空的,但是您的 syso.println 无论如何都只显示输入数组中的所有元素。另一个问题是,如果您对两个数组使用相同的索引,您的垃圾数组中将有元素 0 <= input[i] <= 9 并且它们之间有很多零。总而言之,您的代码应如下所示

int[] garbage = new int[input.length];
int j = 0;
for (int i=0; i < input.length; i++){
    if (input[i] >= 0 && input[i] <= 9){
        garbage[j] = input[i];
        j++;
        System.out.print(garbage[j]);
    }

}

这样,您将看到添加到垃圾中的元素。并且所有零都在数组的末尾。

于 2013-07-31T22:56:20.637 回答
0

您的输出打印出数组中的值,而不管它的值是什么,因为它在您的 if 语句之外,请尝试}在 print 语句之后移动 if 语句的结束,如下所示

for (int i=0; i<input.length; i++){
    if (input[i] < 0 && input[i] > 9){
        garbage[i] = input[i];
    //}  <--- move this to
        int x = input[i];
        System.out.print(x);
    } // <--- here
}

但是,garbage数组中的值现在是您不想要的值(小于 0 和大于 10),如果您打印出这些值,您会找到预期的输出。

如果你想要一个包含你想要的值的数组,那么创建一个数组并以这种方式添加

int[] keeping = new int[input.length];
int j = 0;
for (int i=0; i<input.length; i++){
    if (input[i] > 0 && input[i] <= 9){
        keeping[j] = input[i];
        j++;
        int x = input[i];
        System.out.print(x);
    }
}
于 2013-07-31T22:57:46.990 回答
0

向后退,所以当你删除某些东西时,你不会访问索引

for (int i = sizeOfArray - 1, i >= 0; i--) { if array[i] > 0 删除对象;}

对不起 sudo 代码

于 2013-07-31T22:58:39.033 回答