if...else if...else語句
if語句后面可以跟elseif…else語句,這種語句可以檢測到多種可能的情況。
使用if,else if,else語句的時候,需要注意下面幾點:
if語句至多有1個else語句,else語句在所有的elseif語句之后。
If語句可以有若干個elseif語句,它們必須在else語句之前。
一旦其中一個else if語句檢測為true,其他的else if以及else語句都將跳過執行。
語法
if...else語法格式如下:
if(布爾表達式 1){
//如果布爾表達式 1的值為true執行代碼
}else if(布爾表達式 2){
//如果布爾表達式 2的值為true執行代碼
}else if(布爾表達式 3){
//如果布爾表達式 3的值為true執行代碼
}else {
//如果以上布爾表達式都不為true執行代碼
}
實例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class Test { public static void main(String args[]){ int x = 30 ; if ( x == 10 ){ System.out.print( "Value of X is 10" ); } else if ( x == 20 ){ System.out.print( "Value of X is 20" ); } else if ( x == 30 ){ System.out.print( "Value of X is 30" ); } else { System.out.print( "This is else statement" ); } } } |
以上代碼編譯運行結果如下:
1
|
Value of X is 30 |
嵌套的if…else語句
使用嵌套的if-else語句是合法的。也就是說你可以在另一個if或者elseif語句中使用if或者elseif語句。
語法
嵌套的if…else語法格式如下:
if(布爾表達式 1){
////如果布爾表達式 1的值為true執行代碼
if(布爾表達式 2){
////如果布爾表達式 2的值為true執行代碼
}
}
你可以像 if 語句一樣嵌套 else if...else。
實例
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Test { public static void main(String args[]){ int x = 30 ; int y = 10 ; if ( x == 30 ){ if ( y == 10 ){ System.out.print( "X = 30 and Y = 10" ); } } } } |
以上代碼編譯運行結果如下:
1
|
X = 30 and Y = 10 |
復合 if- else if – else 語句小例子:
百分制轉換為等級制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class IfElseDemo06{ public static void main(String[] args){ int a= 85 ; //聲明int 型變量a 并賦值85 if (a> 90 ){ //條件判斷 System.out.println( "成績" +a+ ",是A 等級" ); } else if (a> 80 ){ //條件判斷 System.out.println( "成績" +a+ ",是B 等級" ); } else if (a> 70 ){ //條件判斷 System.out.println( "成績" +a+ ",是C 等級" ); } else if (a> 60 ){ //條件判斷 System.out.println( "成績" +a+ ",是D 等級" ); } else { System.out.println( "成績" +a+ ",是B 等級" ); } } } |
運行結果如圖所示。
1
|
成績85,是B等級 |
再來總結一下if-else語句的規則:
1)、if后的括號不能省略,括號里表達式的值最終必須返回的是布爾值
2)、如果條件體內只有一條語句需要執行,那么if后面的大括號可以省略,但這是一種極為不好的編程習慣。
3)、對于給定的if,else語句是可選的,else if 語句也是可選的
4)、else和else if同時出現時,else必須出現在else if 之后
5)、如果有多條else if語句同時出現,那么如果有一條else if語句的表達式測試成功,那么會忽略掉其他所有else if和else分支。
6)、如果出現多個if,只有一個else的情形,else子句歸屬于最內層的if語句