Scala program to implement an arithmetic calculator using a match case

Here, we are going to learn how to implement an arithmetic calculator using a match case in Scala programming language?
Submitted by Nidhi, on April 28, 2021

Problem Solution:

Here, we will implement an arithmetic calculator using the match case. Here we will read two numbers and perform the selected operation.

Program/Source Code:

The source code to implement the arithmetic calculator 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 implement arithmetic calculator
// using "match" case

object Sample {
    def main(args: Array[String]) {  
        var ch:Char=0
        var num1:Int=0
        var num2:Int=0
        var result:Int=0
        
        
        print("Choose operation to perform (+,-,*,/,%): ")
        ch=scala.io.StdIn.readChar()
        
        print("Enter first number: ")
        num1=scala.io.StdIn.readInt()
        
        print("Enter second number: ")
        num2=scala.io.StdIn.readInt()
        
        ch match{
            case '+'=> result=num1+num2 
            case '-'=> result=num1-num2
            case '*'=> result=num1*num2
            case '/'=> result=num1/num2
            case '%'=> result=num1%num2
            case _=>printf("Invalid operation.\n")
        }
        println("Result: "+result);
    }
}  

Output:

Choose operation to perform (+,-,*,/,%): *
Enter first number: 10
Enter second number: 20
Result: 200

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 four variables ch, num1, num2, result. Here, we choose operation by entering character and then enter both integer numbers. After that, we performed a selected operation using the match case and print the result on the console screen.

Scala Pattern Matching Programs »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.