在一个二维数组中循环,其范围在0和1之间。

huangapple go评论112阅读模式
英文:

for loop that cycles between 0 and 1 in a 2D Array

问题

我目前正在制作一个国际象棋棋盘,我需要使用双重循环为每个其他单元格分配1或0。我的代码如下:

int[][] board = new int[8][8];

for (int i = 0; i < 8; i++) {
    for (int j = 0; j < 8; j++) {
        board[i][j] = ?;
        println(board[i][j]);
    }
}
英文:

I am currently making a chessboard and I need to assign every other cell with 1 or 0 with a double for loop.
My code looks like this:
(Processing / Java)

int[][] board = new int [8][8];
    
for (int i = 0; i &lt; 8; i++) {
    for (int j = 0; j &lt; 8; j++) {
        board[i][j] = ?;
        println(board[i][j]);
    }
}

答案1

得分: 2

看起来你正在尝试为棋盘分配颜色。

0 - 黑色
1 - 白色

你可以这样做:

如果((i + j) % 2 == 0)
   arr[i][j] = 0;
否则 
   arr[i][j] = 1;
英文:

Looks like you're trying to assign color to a chessBoard.

0 - Black
1 - White

what you can do is,

if((i + j) % 2 == 0)
   arr[i][j] = 0;
else 
   arr[i][j] = 1;

答案2

得分: 2

int[][] board = new int[8][8];

for (int i = 0; i < 8; i++) {
    for (int j = 0; j < 8; j++) {
        board[i][j] = (j + i) % 2;
        System.out.println(board[i][j]);
    }
}
英文:
int[][] board = new int[8][8];

for (int i = 0; i &lt; 8; i++) {
    for (int j = 0; j &lt; 8; j++) {
        board[i][j] = (j+i) % 2;
        System.out.println(board[i][j]);
    }
}

huangapple
  • 本文由 发表于 2020年9月24日 16:46:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64042752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定