Scala - IF ELSE 语句
本章将带您了解 Scala 编程中的条件构造语句。 以下是大多数编程语言中常见的典型决策 IF...ELSE 结构的一般形式。
流程图
下面是条件语句的流程图。
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's,它必须在任何 else if's 之后。
一个"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 语句总是合法的,这意味着您可以在另一个 if 或 else-if 语句中使用 b>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
}
}
尝试以下示例程序来理解 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

