简体   繁体   中英

Recognizing and converting ternary operator to correct if statement

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

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™ .

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM