public class sudoku2 {
static int[][] grid = new int[9][9];
public static void main(String[] args) {
showSudoku();
tryNumber(0, 4, 5);
tryNumber(1, 8, 1);
tryNumber(2, 6, 9);
tryNumber(3, 0, 2);
tryNumber(4, 1, 9);
tryNumber(5, 7, 3);
tryNumber(6, 8, 7);
tryNumber(7, 3, 6);
tryNumber(8, 7, 5);
tryNumber(4, 4, 1);
tryNumber(7, 3, 9);
tryNumber(6, 7, 8);
tryNumber(5, 6, 7);
tryNumber(4, 5, 6);
tryNumber(3, 4, 7);
tryNumber(2, 3, 4);
tryNumber(1, 2, 3);
tryNumber(2, 4, 2);
tryNumber(2, 4, 2);
showSudoku();
}
static void showSudoku() {
System.out.println("-------------------------");
for (int x = 0; x < 9; x++) {
System.out.print("| ");
for (int y = 0; y < 9; y++) {
if (grid[x][y] == 0) {
System.out.print(".");
} else {
System.out.print(grid[x][y]);
}
System.out.print(" ");
if (y % 3 == 2) {
System.out.print("| ");
}
}
System.out.println();
if (x % 3 == 2) {
System.out.println("-------------------------");
}
}
}
static void insert(int x, int y, int zahl) {
if (!(x < 0 || x > 8 || y < 0 || y > 8 || zahl < 1 || zahl > 9) && grid[x][y] == 0) {
grid[x][y] = zahl;
} else {
// Do nothing
}
}
static boolean conflictInRow(int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[x][i] == y)
return true;
}
return false;
}
static boolean conflictInColumn(int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[i][y] == x)
return true;
}
return false;
}
static boolean conflictInSquare(int x, int y) {
int zeile = x - x % 3;
int spalte = y - y % 3;
for (int i = zeile; i < zeile + 3; i++) {
for (int j = spalte; j < spalte + 3; j++)
if (grid[i][j] == 9)
return true;
}
return false;
}
static boolean anyConflict(int x, int y) {
if (conflictInRow(x, y) == true && conflictInColumn(x, y) == true && conflictInSquare(x, y) == true) {
return true;
}
return false;
}
static boolean tryNumber(int x, int y, int zahl) {
if (anyConflict(x, y) == false) {
insert(x, y, zahl);
return true;
}
showSudoku();
return false;
}
}
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>
) to add backticks around text.
See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).