Question

I'm trying to figure out the below code and I'm having trouble with the ternary operator below.

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

Is this correct?

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

The above statement can be represented by

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

            } else {
                System.out.print(Integer.toString(solution[i][j]));
            }
Was it helpful?

Solution

Yes, your "is this correct?" is correct. It's just a removal of some white-space so it will be hard to mess it up. I think that your second statement is correct as well. Putting a ternary inside of a method parameter is a BAD IDEA™.

OTHER TIPS

Yes, it's correct. You just wrote a multiline statement as a single line, there's no difference at all - adding/removing white space has no effect whatsoever. And yes, the expanded version using if/else is equivalent. Why don't you test your code and see that it does, indeed, work correctly?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top