Can I use a conditional statement in a printf statement?

My code contains a switch statement, and in all cases there are else statements. They are all quite short, so I thought about code compression, turning them into conditional statements. The format I was going to was ...

System.out.printf( (conditional-Statement ) );

Here is my if else statement for one of the cases ...

    if (count == 1) {
        System.out.printf("%3d", count);
    } else {
        System.out.printf("%11d", count);
    }

Sort of...

System.out.print((count == 1) ? count : "  " + count);

does not create syntax errors

but it all messed up when I did it ...

System.out.printf((count == 1) ?  "%3d", count : "%11d", count);

Am I trying to do this?

+4
source share
3 answers

Yes it is possible. But recall that the ternary operator returns only one value, not two. What you are trying to do should be done as follows:

System.out.printf((count == 1) ?  "%3d" : "%11d", count);
+9
source

It should be

System.out.printf((count == 1) ?  "%3d": "%11d", count);

count .

, , .

String format = (count == 1) ?  "%3d" : "%11d";
System.out.printf(format, count);
+2

This may be possible with 'String.format', as follows

System.out.print((count==1)? String.format("%3d", count): String.format("%11d", count));
+2
source

Source: https://habr.com/ru/post/1609511/


All Articles