Java if/else語句

Java if語句用於測試條件。它檢查布爾條件為:truefalse。 java中有各種類型的if語句,它們分別如下:

  • if語句
  • if-else語句
  • 嵌套if語句
  • if-else-if語句

Java if語句

Java語言中的if語句用於測試條件。如果條件為true,則執行if語句塊。

語法:

if(condition){
   // if 語句塊 => code to be executed.
}

執行流程如下圖所示 -

1. 示例

public class IfExample {
    public static void main(String[] args) {
        int age = 20;
        if (age > 18) {
            System.out.print("Age is greater than 18");
        }
    }
}

輸出結果如下 -

Age is greater than 18

Java if-else語句

Java if-else語句也用於測試條件。如果if條件為真(true)它執行if塊中的代碼,否則執行else塊中的代碼。

語法:

if(condition){
    //code if condition is true
}else{
    //code if condition is false
}

執行流程如下圖所示 -

示例代碼:

public class IfElseExample {
    public static void main(String[] args) {
        int number = 13;
        if (number % 2 == 0) {
            System.out.println("這是一個偶數");
        } else {
            System.out.println("這是一個奇數");
        }
    }
}

輸出結果如下 -

這是一個奇數

Java if-else-if語句

Java編程中的if-else-if語句是從多個語句中執行一個條件。

語法:

if(condition1){
    //code to be executed if condition1 is true
}else if(condition2){
    //code to be executed if condition2 is true
}else if(condition3){
    //code to be executed if condition3 is true
}
...
else{
    //code to be executed if all the conditions are false
}

執行流程如下圖所示 -

示例:

public class IfElseIfExample {
    public static void main(String[] args) {
        int marks = 65;

        if (marks < 50) {
            System.out.println("fail");
        } else if (marks >= 50 && marks < 60) {
            System.out.println("D grade");
        } else if (marks >= 60 && marks < 70) {
            System.out.println("C grade");
        } else if (marks >= 70 && marks < 80) {
            System.out.println("B grade");
        } else if (marks >= 80 && marks < 90) {
            System.out.println("A grade");
        } else if (marks >= 90 && marks < 100) {
            System.out.println("A+ grade");
        } else {
            System.out.println("Invalid!");
        }
    }
}

輸出結果如下 -

C grade

上一篇: Java運算符 下一篇: Java switch語句