Simple Calculator Program in Java

Write a program in Java to design a calculator machine that accepts two numbers and an arithmetic operator from the user. Finally, it prints the output when the user enters an = sign. Till then, it keeps accepting numbers and operators.

import java.util.Scanner;

class Calculator{

    public static void main(String[] args){

        Scanner in = new Scanner(System.in);

        System.out.print("Enter first number: ");

        double result = Double.parseDouble(in.nextLine());

        while(true){

            System.out.print("Enter operator (+, -, *, /, =): ");

            char op = in.nextLine().charAt(0);

            if (op == '='){

                System.out.println("Result = " + result);

                break;

            }

            System.out.print("Enter next number: ");

            double num = Double.parseDouble(in.nextLine());

            switch(op){

                case '+':

                    result += num;

                    break;

                case '-':

                    result -= num;

                    break;

                case '*':

                    result *= num;

                    break;

                case '/':

                    if (num != 0)

                        result /= num;

                    else

                        System.out.println("Division by zero error!");

                    break;

                default:

                    System.out.println("Invalid operator.");

            }

        }

    }

}

Comments