Java簡明教程系列(15) - 條件語句

流程圖

條件分支結構具有程序要評估或測試的一個或多個條件,當條件爲true時,一組語句被執行,否則執行另一組語句。
大多數編程語言裏的條件分支結構都是按照下面這個通用的流程圖執行:
在這裏插入圖片描述
Java中提供了下面這幾種類型的條件語句。

序號 語句 & 描述
1 if語句if語句由一組布爾表達式組成,後面跟着一條或多條語句。
2 if…else語句if語句可以在後面使用else語句來處理布爾表達式爲false的情形。
3 嵌套if語句我們可以在if和else if語句中嵌套使用if或else if語句。
4 switch語句switch語句允許對變量的值進行比較,不同的值進行不同的處理。

if語句

if語句的語法結構爲:

if(布爾表達式) {
   //當布爾表達式爲true時才執行這裏的語句
}

舉個例子

public class Test {

   public static void main(String args[]) {
      int x = 10;

      if( x < 20 ) {
         System.out.print("This is if statement");
      }
   }
}

程序運行結果輸出如下:

This is if statement.

if…else語句

if…else語句的語法結構爲:

if(布爾表達式) {
   //當布爾表達式爲true時執行這裏的語句
}else {
   //當布爾表達式爲false時執行這裏的語句
}

舉個例子

public class Test {

   public static void main(String args[]) {
      int x = 30;

      if( x < 20 ) {
         System.out.print("This is if statement");
      }else {
         System.out.print("This is else statement");
      }
   }
}

程序運行結果輸出如下:

This is else statement

if…else if…else語句

當有多個條件需要判斷並分別執行不同的代碼時,我們可以使用if…else if…else來處理。

if…else if…else語句的語法結構爲:

if(布爾表達式1) {
   //當布爾表達式1爲true時執行
}else if(Boolean_expression 2) {
   //當布爾表達式2爲true時執行
}else if(Boolean_expression 3) {
   //當布爾表達式3爲true時執行
}else {
   //當上面3個表達式都不爲true時執行
}

舉個例子

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");
      }
   }
}

程序運行結果輸出如下:

Value of X is 30

三目運算符(? :)

我們在前面章節中介紹了可以替代if…else語句的三目運算符:? :,其語法結果爲:

表達式1 ? 表達式2 : 表達式3

注意冒號的使用和位置
爲了確定整個表達式的值,首先對錶達式1求值。

  • 當表達式1爲true時,表達式2的值就是整個表達式的值。
  • 當表達式1爲false時,表達式3的值就是整個表達式的值。

關注公衆號「小白輕鬆學編程」

更多交流,歡迎微信搜索並關注公衆號「小白輕鬆學編程」!
博客裏所有教程會第一時間在公衆號上更新喲,掃碼關注一下吧~

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章