三元運(yùn)算符
三元運(yùn)算符多級(jí)使用,條件運(yùn)算符是右結(jié)合的,也就是說(shuō)酪刀,從右向左分組計(jì)算郑象。
例如:
`a?b:c?d:e;`等價(jià)于`a?b:(c?d:e);`
問題:大于90成績(jī)?yōu)锳属百,60~89成績(jī)?yōu)锽,60以下為C
import java.util.Scanner;
public class Compare {
public static void main(String []args){
System.out.println("請(qǐng)輸入這個(gè)同學(xué)的成績(jī)");
Scanner grade=new Scanner(System.in);
int score=grade.nextInt();
String number=score>100||score<0?"錯(cuò)誤":
score>=90? ("這個(gè)同學(xué)的等級(jí)為A"):
(score>60&&score<90?"這個(gè)同學(xué)的等級(jí)為B":
"這個(gè)同學(xué)的等級(jí)為C");
System.out.println(number);
}
}
三種判斷對(duì)比
三元運(yùn)算符
class TestSanyuan{
public static void main (String[] args){
//三元運(yùn)算符號(hào)
int gender = 1;
char gText = gender == 1?'男':'女';
System.out.println("三元運(yùn)算符號(hào)結(jié)果:"+gText);
}
}
if語(yǔ)句
class Testif{
public static void main (String[] args){
int gender = 1;
char genderText = ' ';
if(gender == 1){
genderText = '男';
}else{
genderText = '女';
}
System.out.println(genderText);
}
}
switch語(yǔ)句
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);
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者