我怎样才能测试该行是否在二维数组中?

时间:2015-09-24 05:50:57

标签: java arrays multidimensional-array

我试图测试数组中的每一行,看看它们是偶数还是奇数。如果行是偶数我想要将行的元素中的随机值更改为0.如果行是奇数我想将元素更改为1.我已经能够创建元素并打印出来但我坚持如何测试行。我知道测试一个数字是否是你使用的(i%2 == 0),但我不确定我应该使用什么编码。

  public static void main(String[] args) {

    int[][] box;
    box = new int[2][2];

    int row;
    int column;

    for (row = 0; row < box.length; row++) {
        for (column = 0; column < box[row].length; column++) {
            box[row][column] = (int) (Math.random() * 100);
        }
    }
   //where im having issues
    // i get error 'bad operand types for binary operator'

     if (box[row] % 2 == 0) {
        for (row = 0; row< box.length;row++){
           box[row][column] = [0][];
        }
     }
    else{
        for(row = 0; row < box.length; row++){
            box[row][column] = [1][];
        }
    }      

    for (row = 0; row < box.length; row++) {
        for (column = 0; column < box[row].length; column++) {
            System.out.print(box[row][column] + " ");
        }
        System.out.println();
    }
}
}

1 个答案:

答案 0 :(得分:0)

你可以使用Arrays内置函数fill(int[],value),它接受​​两个参数,第一个1d数组,第二个值填充

//also if you are checking is row is even or odd divide row not box[row]
if (row % 2 == 0) {
        Arrays.fill(box[row],0);//set 0 to every element in this wor
}
else{  
        Arrays.fill(box[row],1);//set 1 to every element in this wor        
}