Java 條件語句
- if
- if…else
- if…else if…else
- if…else嵌套
if
語法格式:
if(表達式){
//如果表達式結果位true 那么執行這里的代碼
}
示例
public class Test { public static void main(String args[]){ int x = 10; if( x < 20 ){ System.out.print("這是 if 語句"); } } }
if…else
語法格式:
if(布爾表達式){
//true
}else{
//false
}
示例
public class Test { public static void main(String args[]){ int x = 30; if( x < 20 ){ System.out.print("這是 if 語句"); }else{ System.out.print("這是 else 語句"); } } }
if…else if…else
語法格式:
if(布爾表達式 1){
//如果布爾表達式 1的值為true執行代碼
}else if(布爾表達式 2){
//如果布爾表達式 2的值為true執行代碼
}else if(布爾表達式 3){
//如果布爾表達式 3的值為true執行代碼
}else {
//如果以上布爾表達式都不為true執行代碼
}
注意:
- 最多有一個else語句
- 可以有若干個else if語句,但必須再else之前
- 一旦其中一個else if語句檢測為true,其他的else if以及else都會被跳過。
示例
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("這是 else 語句"); } } }
if…else嵌套
語法格式:
if(布爾表達式 1){
////如果布爾表達式 1的值為true執行代碼
if(布爾表達式 2){
////如果布爾表達式 2的值為true執行代碼
}
}
示例
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"); } } } }
