if語句后面可以跟elseif…else語句,這種語句可以檢測到多種可能的情況。
使用if,else if,else語句的時候,需要注意下面幾點:
if...else語法格式如下:
if(布爾表達式 1){ //如果布爾表達式 1的值為true執(zhí)行代碼 }else if(布爾表達式 2){ //如果布爾表達式 2的值為true執(zhí)行代碼 }else if(布爾表達式 3){ //如果布爾表達式 3的值為true執(zhí)行代碼 }else { //如果以上布爾表達式都不為true執(zhí)行代碼 }
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"); } } }
以上代碼編譯運行結(jié)果如下:
Value of X is 30
![]() | ![]() .. 定價:¥45 優(yōu)惠價:¥42 更多書籍 |
![]() | ![]() .. 定價:¥225 優(yōu)惠價:¥213 更多書籍 |