Scala IF /en. ELSE statement
Scala IF /en. ELSE statement block of code is determined by the results of one or more statements of (True or False).
The following figure can be a simple understanding of the execution of the conditional statement:
if statement
if there is a block of statements and statements following Boolean expressions.
grammar
Syntax if the statement is as follows:
if(布尔表达式) { // 如果布尔表达式为 true 则执行该语句块 }
If the Boolean expression is true then execute a block of statements inside the curly braces, otherwise skip a block of statements inside the curly braces, the statement is executed after the block braces.
Examples
object Test { def main(args: Array[String]) { var x = 10; if( x < 20 ){ println("x < 20"); } } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test x < 20
if /en. else statement
After the if statement can be followed by else statements, statements can be executed within the block else to false when the Boolean expression.
grammar
if /en. else syntax is as follows:
if(布尔表达式){ // 如果布尔表达式为 true 则执行该语句块 }else{ // 如果布尔表达式为 false 则执行该语句块 }
Examples
object Test { def main(args: Array[String]) { var x = 30; if( x < 20 ){ println("x 小于 20"); }else{ println("x 大于 20"); } } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test x 大于 20
if /en. else if /en. else statement
After the if statement can be followed else if /en. else statement, in the case of multiple conditional statements useful.
grammar
if /en. else if /en. else syntax is as follows:
if(布尔表达式 1){ // 如果布尔表达式 1 为 true 则执行该语句块 }else if(布尔表达式 2){ // 如果布尔表达式 2 为 true 则执行该语句块 }else if(布尔表达式 3){ // 如果布尔表达式 3 为 true 则执行该语句块 }else { // 如果以上条件都为 false 执行该语句块 }
Examples
object Test { def main(args: Array[String]) { var x = 30; if( x == 10 ){ println("X 的值为 10"); }else if( x == 20 ){ println("X 的值为 20"); }else if( x == 30 ){ println("X 的值为 30"); }else{ println("无法判断 X 的值"); } } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test X 的值为 30
if /en. else statement nested
Nested if /en. else statements can be embedded in one or more of if statements within the if statement.
grammar
Nested if /en. else statement syntax is as follows:
if(布尔表达式 1){ // 如果布尔表达式 1 为 true 则执行该语句块 if(布尔表达式 2){ // 如果布尔表达式 2 为 true 则执行该语句块 } }
else if /en. else statement nested similar nested if /en. else statement.
Examples
object Test { def main(args: Array[String]) { var x = 30; var y = 10; if( x == 30 ){ if( y == 10 ){ println("X = 30 , Y = 10"); } } } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test X = 30 , Y = 10