標籤:gpo public static if語句 格式 輸出 blog rgs amp
if條件陳述式分為三種文法格式,每一種格式都有它自身的特點
1.if語句
if語句是指如果滿足某種條件,就進行某種處理
公式:
if (條件陳述式){
執行語句;
……
}
1 public class Pd{2 public static void main(String[] args){3 int time = 5;4 if(time<7){5 System.out.println("鬧鐘響了,該起床了!");6 }7 }8 }
結果:會輸出鬧鐘響了,該起床了!
2.if…else語句
if (判斷條件){
執行語句1
……
}else{
執行語句2
……
}
1 public class Pd { 2 3 public static void main(String[] args) { 4 int a = 4,b = 7; //定義兩個int整型變數 5 int max; 6 if(a>b){ 7 max = a; 8 }else{ 9 max = b;10 System.out.println(max);11 }12 } 13 }
結果:會輸出7
3.if…else if…else語句
if (判斷條件1) {
執行語句1
} else if (判斷條件2) {
執行語句2
}
...
else if (判斷條件n) {
執行語句n
} else {
執行語句n+1
}
1 public class Pd{ 2 public static void main(String[] args){ 3 int score = 103; 4 if(score>=90 && score<=100){ 5 System.out.println("優秀"); 6 }else if(score>=60 && score<90){ 7 System.out.println("合格"); 8 }else if(score>=0 && score<60){ 9 System.out.println("不及格");10 }else{11 System.out.println("錯誤或異常");12 }13 }14 }
結果:會輸出錯誤或異常
java 選擇結構if