我试图测试数组中的每一行,看看它们是偶数还是奇数。如果行是偶数,我想将行元素的随机值更改为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();
}
}
}
你可以使用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
}