Java if語句用于根據(jù)條件執(zhí)行一個代碼塊。
下面是Java if語句的最簡單形式:
if(condition)
statement;
condition
是一個布爾表達式。如果 condition
是 true
那么執(zhí)行語句
。
如果 condition
是 false
,那么繞過語句
。
以下代碼根據(jù)an的值輸出消息整數(shù)。 它使用if語句來執(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語句經(jīng)常用于比較兩個變量。下面的代碼定義了兩個變量, x
和 y
,它使用if語句來比較它們并打印出消息。
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("===");
}
}
}
此程序生成的輸出如下所示:
我們還可以使用布爾值來控制if語句。boolean
變量的值足以控制if語句。
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.");
}
}
}
沒有必要寫如下的 if
語句:
if(b == true) ...
此程序生成的輸出如下所示:
if
語句是條件分支語句。我們可以在if語句中添加else語句。
這里是 if-else
語句的一般形式:
if (condition)
statement1;
else
statement2;
else
子句是可選的。 每個語句可以是單個語句或復(fù)合語句用花括號括起來(一個塊)。 只有一個語句可以直接出現(xiàn)在 if
或 else
之后。要包含更多語句,您需要創(chuàng)建一個塊,如在這個片段中。
以下示例顯示如何使用Java if else
語句。
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
語句時包含花括號是很好的,即使每個子句中只有一個語句。
if else梯形語句用于在多個條件下工作。
if-else-if梯形如下:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;
這里是一個使用 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
語句在另一個if
語句或 else
。
以下代碼使用嵌套if語句來比較值。
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);
}
}
輸出:
更多建議: