if語句
一個if語句包含一個布爾表達式和一條或多條語句。
語法
If語句的用語法如下:
if(布爾表達式)
{
//如果布爾表達式為true將執(zhí)行的語句
}
如果布爾表達式的值為true,則執(zhí)行if語句中的代碼塊。否則執(zhí)行If語句塊后面的代碼。
1
2
3
4
5
6
7
8
9
10
|
public class Test { public static void main(String args[]){ int x = 10 ; if ( x < 20 ){ System.out.print( "這是 if 語句" ); } } } |
以上代碼編譯運行結果如下:
1
|
這是 if 語句 |
if...else語句
if語句后面可以跟else語句,當if語句的布爾表達式值為false時,else語句塊會被執(zhí)行。
語法
if…else的用法如下:
if(布爾表達式){
//如果布爾表達式的值為true
}else{
//如果布爾表達式的值為false
}
實例
1
2
3
4
5
6
7
8
9
10
11
12
|
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語句示例
假設我到辦公室里問黃文強在不在?如果他在的話會說在,不在的時候有熱心同事回答了一句“他不在”,那我就不立刻明白了。我們用程序模擬一下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class demo { public static void main(String[] args) { //設置黃文強不在 boolean flag = false ; System.out.println( "開始" ); if (flag){ System.out.println( "在" ); } else { System.out.println( "他不在" ); } System.out.println( "結束" ); } } |