public class magicSquare { public static void main(String[] args) { int[][] board = new int[3][3]; for ( board[0][0] = 1; board[0][0] <= 9; board[0][0]++ ) for ( board[0][1] = 1; board[0][1] <= 9; board[0][1]++ ) for ( board[0][2] = 1; board[0][2] <= 9; board[0][2]++ ) for ( board[1][0] = 1; board[1][0] <= 9; board[1][0]++ ) for ( board[1][1] = 1; board[1][1] <= 9; board[1][1]++ ) for ( board[1][2] = 1; board[1][2] <= 9; board[1][2]++ ) for ( board[2][0] = 1; board[2][0] <= 9; board[2][0]++ ) for ( board[2][1] = 1; board[2][1] <= 9; board[2][1]++ ) for ( board[2][2] = 1; board[2][2] <= 9; board[2][2]++ ) if ( isCorrect(board) ) PrintBoard(board); } public static boolean isCorrect(int[][] board) { int count; // #1 must appear once count = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (board[i][j] == 1) count++; if (count != 1) return false; // #2 must appear once count = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (board[i][j] == 2) count++; if (count != 1) return false; // #3 must appear once count = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (board[i][j] == 3) count++; if (count != 1) return false; // #4 must appear once count = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (board[i][j] == 4) count++; if (count != 1) return false; // #5 must appear once count = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (board[i][j] == 5) count++; if (count != 1) return false; // #6 must appear once count = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (board[i][j] == 6) count++; if (count != 1) return false; // #7 must appear once count = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (board[i][j] == 7) count++; if (count != 1) return false; // #8 must appear once count = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (board[i][j] == 8) count++; if (count != 1) return false; // #9 must appear once count = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (board[i][j] == 9) count++; if (count != 1) return false; // row 1 sum = 15 if ( board[0][0] + board[0][1] + board[0][2] != 15 ) return false; // row 2 sum = 15 if ( board[1][0] + board[1][1] + board[1][2] != 15 ) return false; // row 3 sum = 15 if ( board[2][0] + board[2][1] + board[2][2] != 15 ) return false; // column 1 sum = 15 if ( board[0][0] + board[1][0] + board[2][0] != 15 ) return false; // column 2 sum = 15 if ( board[0][1] + board[1][1] + board[2][1] != 15 ) return false; // column 3 sum = 15 if ( board[0][2] + board[1][2] + board[2][2] != 15 ) return false; // Diagonal sum = 15 if ( board[0][0] + board[1][1] + board[2][2] != 15 ) return false; // Anti-diagonal sum = 15 if ( board[2][0] + board[1][1] + board[0][2] != 15 ) return false; return true; } public static void PrintBoard(int[][] board) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) System.out.print(board[i][j] + " "); System.out.println(); } System.out.println(); } }