Scala条件判断语句

下面是一个典型的决策中IF...ELSE结构的一般形式使用在大多数的编程语言中:

if 语句:
if 语句包含一个布尔表达式后跟一个或多个语句。

语法:
一个 if 语句的语法:
if(Boolean_expression)
{
   // Statements will execute if the Boolean expression is true
}
如果布尔表达式的值为true,那么if语句里面的代码模块将被执行。如果不是这样,第一组码if语句结束后(右大括号后)将被执行。
示例:
object Test {
   def main(args: Array[String]) {
      var x = 10;

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

if...else语句:
if语句可以跟着一个可选的else语句,当 else 块执行时,布尔表达式条件是假的。

语法:
if...else的语法是:
if(Boolean_expression){
   //Executes when the Boolean expression is true
}else{
   //Executes when the Boolean expression is false
}

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

      if( x < 20 ){
         println("This is if statement");
      }else{
         println("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.
}

示例:

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

if ... else语句嵌套:
它始终是合法的嵌套 if-else 语句,这意味着可以使用一个 if 或 else if 在另一个if 或 else 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
   }
}

可以嵌套else if...else在if语句中,反之也可以。
示例:


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

         if( x == 30 ){
            if( y == 10 ){
            	println("X = 30 and Y = 10");
            }
         }
   }
}
QQ群交流:214862451
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值