public class test { public static void main(String[] args) { int i =0 ; for( i =0 ; i<=25; i++) { System.out.printf("%d", i); (i%5==0)?System.out.println():System.out.print(" "); } }
0 1 2 3 4
5 6 7 8 9
...
回答1:
The message you get is not very clear. And neither is Oracle's Tutorial statement that ?: "can be thought of as shorthand for an if-then-else statement" because it is a little more limited.
From the JLS, 15.25 Conditional Operator ? : "Note that it is a compile-time error for either the second or the third operand expression to be an invocation of a void method." So the bpttom line is that if you want to conditionally evaluate one of two void methods, then you have to use if/else.
(A general point - which you should feel free to ignore for now - is that ?: will form an expression which always has a type. if/else on the other hand forms a statement that has no type associated with it.)
回答2:
Well, they only need to be castable to the same type without loss if data, i.e. implicitly castable, which includes subclasses. But you can not write
? true : 1
? "hello" : 'w' //note that one of them is a String, and the other is a char (character).
And so on.
But why go into the complex when we are just describing the basics, implicitly castable is one of the things beginners usually have problems with.
And I think ?: is less OS dependent then +, which I believe is processor dependent and behaves exactly the same for all processors.