easyProgramming Fundamentals
Switch Statements
Build a small calculator supporting addition, subtraction, and multiplication.
Work through the cases
3 examplesInput notation
Two integers followed by an operator: +, -, or *.Expected result
The calculated integer.Case 1
Input
8 3 -
Expected output
5
Case 2
Input
4 6 *
Expected output
24
Case 3
Input
-4 6 +
Expected output
2
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Use the operator to choose addition, subtraction, or multiplication. Time and space: O(1).
import java.util.*;
public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); long x=in.nextLong(), y=in.nextLong(); String op=in.next(); switch(op){ case "+": System.out.println(x+y); break; case "-": System.out.println(x-y); break; case "*": System.out.println(x*y); } } }Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.