int[][] board = new int[i][i];
int row = 0;
int col = i / 2;
int num = 1;
while (num <= i * i) {
board[row][col] = num;
num++;
int tCol = (col + 1) % i;
int tRow = (row - 1) >= 0 ? row - 1 : i - 1;
if (board[tRow][tCol] != 0) {
row = (row + 1) % i;
} else {
row = tRow;
col = tCol;
}
}
System.out.println("Number of wins: " + ifCorrect);
M.Print(i, board);
上面的代码是创建魔方的代码。我如何以更简单的形式编写下面的代码,以便java中的初学者理解?
int tRow = (row - 1) >= 0 ? row - 1 : i - 1;
答案 0 :(得分:1)
简化行(适合初学者程序员):
int tRow = (row - 1) >= 0 ? row - 1 : i - 1;
让我们扩展三元表达式,并将(row-1) >= 0
简化为等效的row >= 1
:
int tRow;
if (row >= 1) {
tRow = row-1;
} else {
tRow = i - 1;
}