Q:

Scala program to implement an arithmetic calculator using a match case

belongs to collection: Scala Pattern Matching Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 chnum1num2result. 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Scala program to check the given character is vowe...