How to write code to implement a calculator in Java?

Here is a simple example of Java calculator code.

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter the first number: ");
        double num1 = scanner.nextDouble();
        
        System.out.println("Enter the second number: ");
        double num2 = scanner.nextDouble();
        
        System.out.println("Enter the operation (+, -, *, /): ");
        char operation = scanner.next().charAt(0);
        
        double result = 0;
        
        switch(operation) {
            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 operation.");
        }
        
        System.out.println("Result: " + result);
        
        scanner.close();
    }
}

This code takes in two numbers and an operator from the user, performs the corresponding operation based on the operator, and finally outputs the result. You can modify and expand this code according to your needs.

bannerAds