是的,三元运算,在运算时会判断冒号两边的类型是否相同,如果不同,那么他会自动帮你提升类型,所以
你的第一个问题的,打印的是68,而不是D
如果你要输出D,应将冒号后面的number做char类型的强制转换;就可以输出D了
代码如下:
public class OperateTest {
public static void main(String[] args) {
int number = 13;
char ch1 = 'A', ch2='E';
System.out.print("I want to get a char: ");
System.out.println(number>10?(char)(number-10+'A'):(char)number);
System.out.print("I want to get a char: ");
System.out.println((char)(number>10?(number-10+'A'):number));
System.out.print("I want to get a char: ");
System.out.println(ch1<ch2?(int)(ch1+'A'):ch2);
System.out.print("I want to get a char: ");
System.out.println(number>10?(char)(number-10+'A'):(char)number);
}
} |