Write a Program to Make a Simple Calculator in Java Programming Language | Solved Programming Exercises
In this tutorial we will write a program in Java Language to build a simple calculator. We will take two numbers from user and an operator. if operator is ‘+’ then add both numbers and so on.
We will use Netbeans IDE For Development. It is very simple and easy to use IDE for Java Development.
How to install Netbeans IDE? How to Install JDK? Learn From following video.
So let’s Code in Java Programming Language.
Open Netbeans IDE and Create a Java New Project “CalculatorinJava”. It will show following code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package calculatorinjava;
import java.util.Scanner;
/**
*myustaadg.com
* @author mohammadumar
*/
public class CalculatorinJava {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
}
}
Now lets take input from user. To take input in Java From user we will use Scanner Class.
Scanner scan = new Scanner(System.in);
int a,b;
char op;
System.out.print("Enter First Number = ");
a = scan.nextInt();
System.out.print("Enter Any Operator(+,-,*,/) = ");
op = scan.next().charAt(0);
System.out.print("Enter Second Number = ");
b = scan.nextInt();
In above code, we created Scanner class object to take input from user.
Now let’s apply if-else if condition to check whether an operator is +, -, *, /.
if(op == '+')
{
System.out.println("Sum = " + (a+b));
}
else if(op == '-')
{
System.out.println("Minus = " + (a-b));
}
else if(op == '*')
{
System.out.println("Mul = " + (a*b));
}
else if(op == '/')
{
if(b == 0)
{
System.out.println("Cannot Divide by Zero");
}
else
{
System.out.println("Sum = " + (a/b));
}
}
else
{
System.out.println("Invalid Operator");
}
Copy the Complete Java Code From Here.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package calculatorinjava;
import java.util.Scanner;
/**
* myustaadg.com
* @author mohammadumar
*/
public class CalculatorinJava {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a,b;
char op;
System.out.print("Enter First Number = ");
a = scan.nextInt();
System.out.print("Enter Any Operator(+,-,*,/) = ");
op = scan.next().charAt(0);
System.out.print("Enter Second Number = ");
b = scan.nextInt();
if(op == '+')
{
System.out.println("Sum = " + (a+b));
}
else if(op == '-')
{
System.out.println("Minus = " + (a-b));
}
else if(op == '*')
{
System.out.println("Mul = " + (a*b));
}
else if(op == '/')
{
if(b == 0)
{
System.out.println("Cannot Divide by Zero");
}
else
{
System.out.println("Sum = " + (a/b));
}
}
else
{
System.out.println("Invalid Operator");
}
}
}
Hope you will learn something from Here.