0
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;
4

1 回答 1

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;
}
于 2016-11-09T18:04:42.027 回答