Here, we will demonstrate the match statement. The match statement is similar to the switch statement of other programming languages. Here, we will define specific cases. In the match statement case underscore (case _) is used for the default case.
The source code to demonstrate the match statement is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to demonstrate the match statement
object Sample{
def main(args:Array[String]){
var num:Int = 0
print("Enter Number: ")
num=scala.io.StdIn.readInt()
num match{
case 1 => println("One")
case 2 => println("Two")
case 3 => println("Three")
case 4 => println("Four")
case _ => println("Unknown Number")
}
}
}
Output:
Enter Number: 3
Three
Explanation:
In the above program, we used an object-oriented approach to create the program. Here, we created an object Sample. We defined main() function. The main() function is the entry point for the program.
In the main() function, we created an integer variable num, which is initialized with 0. Here, we read the value of the num variable and then match entered value in specified cases. After that, we printed the appropriate message based on the matched case on the console screen.
Program/Source Code:
The source code to demonstrate the match statement is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
Output:
Explanation:
In the above program, we used an object-oriented approach to create the program. Here, we created an object Sample. We defined main() function. The main() function is the entry point for the program.
In the main() function, we created an integer variable num, which is initialized with 0. Here, we read the value of the num variable and then match entered value in specified cases. After that, we printed the appropriate message based on the matched case on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer