Scala program to read a weekday number and print weekday name using match case

Here, we are going to learn how to read a weekday number and print weekday name using match case in Scala programming language?
Submitted by Nidhi, on April 28, 2021 [Last updated : March 10, 2023]

Scala – Find Weekday's Name

Here, we will read a weekday number from the user and print the weekday name using the match case on the console screen.

Scala code to read a weekday number and print weekday name using match case

The source code to read a weekday number and print a weekday name using the match case is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to read weekday number and 
// print weekday name using "match" case

object Sample {
    def main(args: Array[String]) {  
        var weekNum:Int=0
        
        print("Enter week number: ")  
        weekNum=scala.io.StdIn.readInt()
        
        weekNum match{  
            case 1 => println("Sunday")  
            case 2 => println("Monday")  
            case 3 => println("Tuesday")  
            case 4 => println("Wednesday")  
            case 5 => println("Thursday")  
            case 6 => println("Friday")  
            case 7 => println("Saturday")  
            case _ => println("Unknown Week Number")  
        }
    }  
}  

Output

Enter week number: 3
Tuesday

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 weekNum, initialized with 0. Then we read the week number from the user and match the corresponding case using the match case. After that, we printed the appropriate weekday name on the console screen.

Scala Pattern Matching Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.