Scala - if else 語句



本章將帶您瞭解 Scala 程式設計中的條件構造語句。以下是大多數程式語言中常見的典型決策 if...else 結構的一般形式。

流程圖

以下是條件語句的流程圖。

Scala IF...ELSE Structure

if 語句

“if”語句由一個布林表示式後跟一個或多個語句組成。

語法

“if”語句的語法如下所示。

if(Boolean_expression) {
   // Statements will execute if the Boolean expression is true
}

如果布林表示式計算結果為真,則將執行“if”表示式內部的程式碼塊。否則,將執行“if”表示式結束後的第一組程式碼(在結束花括號之後)。

嘗試以下示例程式以瞭解 Scala 程式語言中的條件表示式(if 表示式)。

示例

object Demo {
   def main(args: Array[String]) {
      var x = 10;

      if( x < 20 ){
         println("This is if statement");
      }
   }
}

將上述程式儲存在 Demo.scala 中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

輸出

This is if statement

If-else 語句

“if”語句後可以跟一個可選的else語句,當布林表示式為假時,該語句將執行。

語法

if...else 的語法如下所示:

if(Boolean_expression){
   //Executes when the Boolean expression is true
} else{
   //Executes when the Boolean expression is false
}

嘗試以下示例程式以瞭解 Scala 程式語言中的條件語句(if-else 語句)。

示例

object Demo {
   def main(args: Array[String]) {
      var x = 30;

      if( x < 20 ){
         println("This is if statement");
      } else {
         println("This is else statement");
      }
   }
}

將上述程式儲存在 Demo.scala 中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

輸出

This is else statement

If-else-if-else 語句

“if”語句後可以跟一個可選的“else if...else”語句,這對於使用單個 if...else if 語句測試各種條件非常有用。

使用 if、else if、else 語句時,需要注意以下幾點。

  • 一個“if”可以有零個或一個“else”,並且它必須位於任何“else if”之後。

  • 一個“if”可以有零個到多個“else if”,並且它們必須位於“else”之前。

  • 一旦“else if”成功,就不會測試任何剩餘的“else if”或“else”。

語法

以下是“if...else if...else”的語法:

if(Boolean_expression 1){
   //Executes when the Boolean expression 1 is true
} else if(Boolean_expression 2){
   //Executes when the Boolean expression 2 is true
} else if(Boolean_expression 3){
   //Executes when the Boolean expression 3 is true
} else {
   //Executes when the none of the above condition is true.
}

嘗試以下示例程式以瞭解 Scala 程式語言中的條件語句(if-else-if-else 語句)。

示例

object Demo {
   def main(args: Array[String]) {
      var x = 30;

      if( x == 10 ){
         println("Value of X is 10");
      } else if( x == 20 ){
         println("Value of X is 20");
      } else if( x == 30 ){
         println("Value of X is 30");
      } else{
         println("This is else statement");
      }
   }
}

將上述程式儲存在 Demo.scala 中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

輸出

Value of X is 30

巢狀 if-else 語句

巢狀if-else語句始終是合法的,這意味著您可以在另一個ifelse-if語句中使用一個ifelse-if語句。

語法

巢狀 if-else 的語法如下所示:

if(Boolean_expression 1){
   //Executes when the Boolean expression 1 is true
   
   if(Boolean_expression 2){
      //Executes when the Boolean expression 2 is true
   }
}

嘗試以下示例程式以瞭解 Scala 程式語言中的條件語句(巢狀 if 語句)。

示例

object Demo {
   def main(args: Array[String]) {
      var x = 30;
      var y = 10;
      
      if( x == 30 ){
         if( y == 10 ){
            println("X = 30 and Y = 10");
         }
      }
   }
}

將上述程式儲存在 Demo.scala 中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

輸出

X = 30 and Y = 10
廣告