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);

the code above is the code to create a magic square. How can I write the code below in a more simpler form that for a beginner in java to understand ?

int tRow = (row - 1) >= 0 ? row - 1 : i - 1;
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

1

To simplify the line (for beginner programmers):

int tRow = (row - 1) >= 0 ? row - 1 : i - 1;

Let's expand the ternary expression, and also simplify (row-1) >= 0 to the equivalent row >= 1:

int tRow;
if (row >= 1) {
    tRow = row-1;
} else {
    tRow = i - 1;
}
Birchlabs
  • 7,437
  • 5
  • 35
  • 54
  • Sorry @Tunaki; you've correctly caught that I wrote this too quickly and without referring carefully enough to the original code. I've now edited my answer. – Birchlabs Nov 09 '16 at 18:07