一:基本選擇結構if
案例:如果Java考試成績大於98分則獎勵MP4
1 public class anli{ 2 public static void main(String[] args) { 3 Scanner input=new Scanner(System.in); 4 System.out.println("請輸入張浩的Java考試成績:"); 5 int score=input.nextInt(); 6 //如果成績大於98分,獎勵MP4 7 if(score>98){ 8 System.out.println("獎勵MP4"); 9 } 10
語法:
if(條件){
//代碼塊
}
注意:
1.條件的結果必須是布爾值
2.代碼塊中只有一條語句時建議不省略{}
二:邏輯運算符:
&&:並且
a&&b:a和b兩個表達式同時成立(同時為true)整個表達式(a && b)才為true
||:或者
a||b:a和b兩個表達式其中有一個成立時整個表達式(a||b)為true
!:非
!a:表達式結果取相反值
接下來展示案例:張浩的Java成績大於98分,而且音樂成績大於80分,或者Java成績等於100分,音樂成績大於70老師都會獎勵他
1 public class B3C02 { 2 3 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 System.out.println("請輸入Java的成績:"); 7 int java=input.nextInt(); 8 System.out.println("請輸入muisc的成績:"); 9 int muisc=input.nextInt(); 10 if((java>98 && muisc>80)||(java==100 && muisc>70)){ 11 System.out.println("獎勵一個MP4"); 12 }
三:if else
語法:
if (條件) {
//代碼塊1
}else{
//代碼塊2
}
四:多重if選擇結構
語法:
if ( 成績>=80) {
//代碼塊1
}
else if (成績>=60) {
//代碼塊2
}
else {
//代碼塊3
}
案例如下
1 public class B3C03 { 2 3 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 System.out.println("請輸入成績:"); 7 int chengji=input.nextInt(); 8 if(chengji>=80){ 9 System.out.println("良好"); 10 }else if(chengji>=60) 11 { 12 System.out.println("中等"); 13 }else if(chengji<60){ 14 System.out.println("差"); 15 16 } 17 18 } 19 20 }
五:嵌套if選擇結構
語法:
if(條件1) {
if(條件2) {
//代碼塊1
} else {
//代碼塊2
}
} else {
//代碼塊3
}
