Dart 程式設計 - if else 語句



else…if 階梯 用於測試多個條件。以下是其語法。

if (boolean_expression1) { 
   //statements if the expression1 evaluates to true 
} 
else if (boolean_expression2) { 
   //statements if the expression2 evaluates to true 
} 
else { 
   //statements if both expression1 and expression2 result to false 
} 

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

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

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

  • 一旦一個else…if條件成立,就不會再測試剩餘的else…ifelse

示例 - else…if 階梯

以下程式程式碼檢查給定值是正數、負數還是零。

void main() { 
   var num = 2; 
   if(num > 0) { 
      print("${num} is positive"); 
   } 
   else if(num < 0) { 
      print("${num} is negative"); 
   } else { 
      print("${num} is neither positive nor negative"); 
   } 
}  

成功執行上述程式碼後將顯示以下輸出。

2 is positive
dart_programming_decision_making.htm
廣告