Write a Java program to create a simple calculator


This program is a simple calculator that allows the user to perform basic arithmetic operations (+, -, *, /) as well as exponentiation (^) on two input numbers.

  • The program first prompts the user to enter two numbers (A and B) and an operator to perform on them. It then displays the numbers and operator entered by the user and calculates and displays the result of the operation.
  • The program checks the operator entered by the user and performs the corresponding operation. If the operator is invalid, it displays an error message.
  • One thing to note is that the program uses a loop to perform exponentiation, which calculates the power of the first number (A) to the second number (B). The loop iterates B times and multiplies the result by A each time. The final result is then printed.

Overall, this program is a useful tool for performing basic arithmetic operations and exponentiation.

Source Code

import java.util.Scanner;
class Calculator
{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int p = 1; 
		System.out.print("Enter the A Numbers :");
		double num1 = in.nextDouble();   
		System.out.print("Enter the B Numbers :");
		double  num2 = in.nextDouble(); 
		System.out.print("Choose an Operation to Perform. E.g.: +, -, *, /, ^ :");
		char  o = in.next().charAt(0); 		
		System.out.println("A Number = " + num1 );
		System.out.println("B Number = " + num2);
		System.out.println("Operator = " + o);  
		System.out.print("Result : " +  num1+ o + num2 +  " = "); 
		if(o=='+')
		{
			System.out.print(num1+num2);
		}
		else  if(o=='-')
		{
		System.out.print(num1-num2);
		}
		else if(o=='*')
		{
			System.out.print(num1*num2);
		}
		else  if(o=='/')
		{
			System.out.print(num1/num2);
		} 
		else if(o=='^')
		{
		   for(int i=1; i<=num2; i++){
			 p *= num1;
		   } System.out.print(p);
		}
		else
		{
			System.out.print("Invalid Operator.");
		}
 
    }
}

Output

Enter the A Numbers :35
Enter the B Numbers :18
Choose an Operation to Perform. E.g.: +, -, *, /, ^ :*
A Number = 35.0
B Number = 18.0
Operator = *
Result : 35.0*18.0 = 630.0

Example Programs