Java Programming | Creating a Simple Calculator

Join Programming and Development Chat Groups on Uphub.io

Introduction

This is a tutorial for creating a simple calculator in java. The program takes two number along with operator, calculates result and prints it. The program is extendable. Go enjoy the program. Lets begin……

Program for simple calculator in java.


//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class SimpleCalculator {
//void main
public static void main (String[] args)
{
//declare int and char
int a,b,result=0;
char c;

//Declare input as scanner
Scanner input = new Scanner(System.in);

//Take inputs
System.out.println("Enter no. :");
a = input.nextInt();
System.out.println("Enter no. :");
b = input.nextInt();
System.out.println("Enter Operator :");
String st = input.next();
c = st.charAt(0);

//add a switch statement
switch(c)
{
case '+':
result = a+b;
System.out.println("Result = "+result);
break;
case '-':
result = a-b;
System.out.println("Result = "+result);
break;
case 'x':
result = a*b;
System.out.println("Result = "+result);
break;
case '/':
result = a/b;
System.out.println("Result = "+result);
break;
default:
System.out.println("Syntax Error");
}
}
}

Output

Enter no. :
12
Enter no. :
54
Enter Operator :
x
Result = 648

How does it work

  1. You enter two numbers.
  2. You enter operator.
  3. The conditional statement decides the formula and calculates result and prints it.

Extending it

The program can be extended. You can use more numbers or other functions of calculator like square, root,trigonometry, etc to expand it. Go ahead…..

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter numbers.
  5. Declare input as Scanner.
  6. Take the inputs and save it in variables.
  7. Add a Switch Statement.
  8. Add the formula to calculate result.
  9. Add system.out.println() function to print the word.

At the end.

You learnt creating the Java program for Simple Calculator. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Sharing options: