user2016462
user2016462

Reputation: 237

Sudoku algorithm with unfamiliar java syntax

I was looking through a Sudoku solving algorithm when I came across a line with some syntax I haven't seen before.

The line I'm confused about is

    System.out.print(solution[i][j] == 0 ? " " : Integer.toString(solution[i][j]));

I do not understand what the question mark means or anything after the question mark. This line is part of the method

    static void writeMatrix(int[][] solution) {
    for (int i = 0; i < 9; ++i) {
        if (i % 3 == 0)
            System.out.println(" -----------------------");
        for (int j = 0; j < 9; ++j) {
            if (j % 3 == 0)
                System.out.print("| ");
            System.out.print(solution[i][j] == 0 ? " " : Integer.toString(solution[i][j]));

            System.out.print(' ');
        }
        System.out.println("|");
    }
    System.out.println(" -----------------------");
}

I got this code from http://www.colloquial.com/games/sudoku/java_sudoku.html. Any explanations would be appreciated!

Upvotes: 0

Views: 170

Answers (4)

Philippe A
Philippe A

Reputation: 176

 System.out.print(solution[i][j] == 0 ? " " : Integer.toString(solution[i][j])); 

is identical to

    if(solution[i][j] == 0){
        System.out.print(" ");
    }
    else{
        System.out.print(Integer.toString(solution[i][j]));
    }

It is basically an inline way to write an if/else statement.

Upvotes: 1

Demortes
Demortes

Reputation: 160

Basically says that if that value is 0, print " ", if not, print the string representation of whatever that array is storing.

Upvotes: 0

mvp
mvp

Reputation: 116117

This is standard ternary operator, which is present in most languages: C, C++, Java, Perl, etc.

condition ? value_if_true : value_if_false

Upvotes: 4

LNO
LNO

Reputation: 387

It's an if statement basically. It will print out " " if solution[i][j] == 0 and Integer.toString(solution[i][j]) if its not.

Upvotes: 0

Related Questions