三元运算符
三元运算符多级使用,条件运算符是右结合的,也就是说,从右向左分组计算。
例如:
`a?b:c?d:e;`等价于`a?b:(c?d:e);`
问题:大于90成绩为A,60~89成绩为B,60以下为C
import java.util.Scanner;
public class Compare {
public static void main(String []args){
System.out.println("请输入这个同学的成绩");
Scanner grade=new Scanner(System.in);
int score=grade.nextInt();
String number=score>100||score<0?"错误":
score>=90? ("这个同学的等级为A"):
(score>60&&score<90?"这个同学的等级为B":
"这个同学的等级为C");
System.out.println(number);
}
}
三种判断对比
三元运算符
class TestSanyuan{
public static void main (String[] args){
//三元运算符号
int gender = 1;
char gText = gender == 1?'男':'女';
System.out.println("三元运算符号结果:"+gText);
}
}
if语句
class Testif{
public static void main (String[] args){
int gender = 1;
char genderText = ' ';
if(gender == 1){
genderText = '男';
}else{
genderText = '女';
}
System.out.println(genderText);
}
}
switch语句
class Testif{
public static void main (String[] args){
int gender = 1;
char genderText = ' ';
switch(gender){
case 1:
genderText = '男';
break;
case 2:
genderText = '女';
break;
default:
genderText = '人妖';
break;
}
System.out.println(genderText);
}
}
网友评论