Java if語(yǔ)句用于根據(jù)條件執(zhí)行一個(gè)代碼塊。
下面是Java if語(yǔ)句的最簡(jiǎn)單形式:
if(condition)
statement;
condition
是一個(gè)布爾表達(dá)式。如果 condition
是 true
那么執(zhí)行語(yǔ)句
。
如果 condition
是 false
,那么繞過(guò)語(yǔ)句
。
以下代碼根據(jù)an的值輸出消息整數(shù)。 它使用if語(yǔ)句來(lái)執(zhí)行檢查。
public class Main {
public static void main(String args[]) {
int num = 99;
if (num < 100) {
System.out.println("num is less than 100");
}
}
}
此程序生成的輸出如下所示:
If語(yǔ)句經(jīng)常用于比較兩個(gè)變量。下面的代碼定義了兩個(gè)變量, x
和 y
,它使用if語(yǔ)句來(lái)比較它們并打印出消息。
public class Main {
public static void main(String args[]) {
int x, y;
x = 10;
y = 20;
if (x < y){
System.out.println("x is less than y");
}
x = x * 2;
if (x == y){
System.out.println("x now equal to y");
}
x = x * 2;
if (x > y){
System.out.println("x now greater than y");
}
if (x == y){
System.out.println("===");
}
}
}
此程序生成的輸出如下所示:
我們還可以使用布爾值來(lái)控制if語(yǔ)句。boolean
變量的值足以控制if語(yǔ)句。
public class Main {
public static void main(String args[]) {
boolean b;
b = false;
if (b) {
System.out.println("This is executed.");
} else {
System.out.println("This is NOT executed.");
}
}
}
沒(méi)有必要寫如下的 if
語(yǔ)句:
if(b == true) ...
此程序生成的輸出如下所示:
if
語(yǔ)句是條件分支語(yǔ)句。我們可以在if語(yǔ)句中添加else語(yǔ)句。
這里是 if-else
語(yǔ)句的一般形式:
if (condition)
statement1;
else
statement2;
else
子句是可選的。 每個(gè)語(yǔ)句可以是單個(gè)語(yǔ)句或復(fù)合語(yǔ)句用花括號(hào)括起來(lái)(一個(gè)塊)。 只有一個(gè)語(yǔ)句可以直接出現(xiàn)在 if
或 else
之后。要包含更多語(yǔ)句,您需要?jiǎng)?chuàng)建一個(gè)塊,如在這個(gè)片段中。
以下示例顯示如何使用Java if else
語(yǔ)句。
public class Main {
public static void main(String[] argv) {
int i = 1;
if (i > 0) {
System.out.println("Here");
i -= 1;
} else
System.out.println("There");
}
}
]]>
輸出:
在使用 if
語(yǔ)句時(shí)包含花括號(hào)是很好的,即使每個(gè)子句中只有一個(gè)語(yǔ)句。
if else梯形語(yǔ)句用于在多個(gè)條件下工作。
if-else-if梯形如下:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;
這里是一個(gè)使用 if-else-if
梯形圖的程序。
public class Main {
public static void main(String args[]) {
int month = 4;
String value;
if (month == 1 )
value = "A";
else if (month == 2)
value = "B";
else if (month == 3)
value = "C";
else if (month == 4)
value = "D";
else
value = "Error";
System.out.println("value = " + value);
}
}
下面是程序產(chǎn)生的輸出:
嵌套 if
是 if
語(yǔ)句在另一個(gè)if
語(yǔ)句或 else
。
以下代碼使用嵌套if語(yǔ)句來(lái)比較值。
public class Main {
public static void main(String[] argv) {
int i = 10;
int j = 4;
int k = 200;
int a = 3;
int b = 5;
int c = 0;
int d =0;
if (i == 10) {
if (j < 20){
a = b;
}
if (k > 100){
c = d;
}
else{
a = c;
}
} else{
a = d;
}
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
輸出:
更多建議: