|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class Calculator { |
| 4 | + public static void main(String[] args){ |
| 5 | + |
| 6 | + // A SIMPLE CALCULATOR USING JAVA WITH ENHANCED SWITCHES |
| 7 | + |
| 8 | + Scanner scanner = new Scanner(System.in); |
| 9 | + |
| 10 | + // Declare variables |
| 11 | + double num1; |
| 12 | + double num2; |
| 13 | + char operator; |
| 14 | + double result = 0; |
| 15 | + boolean validOperation = true; |
| 16 | + |
| 17 | + //User prompts for getting the numbers and the operator |
| 18 | + System.out.print("Enter the first number: "); |
| 19 | + num1 = scanner.nextDouble(); |
| 20 | + |
| 21 | + System.out.print("Enter the operator (+, -, *, /, ^): "); |
| 22 | + operator = scanner.next().charAt(0); |
| 23 | + |
| 24 | + System.out.print("Enter the second number: "); |
| 25 | + num2 = scanner.nextDouble(); |
| 26 | + |
| 27 | + // Enhanced switch along with exceptional cases |
| 28 | + switch(operator){ |
| 29 | + case '+' -> result = num1 + num2; |
| 30 | + case '-' -> result = num1 - num2; |
| 31 | + case '*' -> result = num1 * num2; |
| 32 | + case '/' -> { |
| 33 | + if(num2 == 0){ |
| 34 | + System.out.println("ZeroDivisionError!"); |
| 35 | + validOperation = false; |
| 36 | + } |
| 37 | + else{ |
| 38 | + result = num1 / num2; |
| 39 | + } |
| 40 | + } |
| 41 | + case '^' -> result = Math.pow(num1, num2); |
| 42 | + default -> { |
| 43 | + System.out.println("Invalid operator!"); |
| 44 | + validOperation = false; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // If operator or number is valid (in case of division, then print the result |
| 49 | + if(validOperation){ |
| 50 | + System.out.printf("%.2f", result); |
| 51 | + } |
| 52 | + |
| 53 | + scanner.close(); |
| 54 | + |
| 55 | + } |
| 56 | +} |
0 commit comments