Calculator

    0

    0

    In this code, the Calculator class exports a static method called main(). This method takes an array of strings as an input. Within this method, the first two lines of code use the Scanner class to input two double values.

    Next, the code calls the static method result(). This method takes a double value as an input and prints out the result.

    Finally, the code calls the main() method again, but this time passes in an operator character as an input. The code then prints out the result of the operation based on the provided character.

    import java.util.Scanner;
    
    public class Calculator {
      public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
    
        System.out.println("Enter first number: ");
        double num1 = scanner.nextDouble();
    
        System.out.println("Enter second number: ");
        double num2 = scanner.nextDouble();
    
        System.out.println("Enter an operator (+, -, *, /): ");
        char operator = scanner.next().charAt(0);
    
        double result;
        switch(operator) {
          case '+':
            result = num1 + num2;
            break;
          case '-':
            result = num1 - num2;
            break;
          case '*':
            result = num1 * num2;
            break;
          case '/':
            result = num1 / num2;
            break;
          default:
            System.out.println("Invalid operator");
            return;
        }
        System.out.println("Result: " + result);
      }
    }
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.