X
    Categories: java

Java Calculator | Addition | Subtraction | Multiply | Divide

 

In the previous java tutorial we have gone through a simple java calculator program.Now this tutorial is a extension for the previous one so please go through it before proceeding any further.

 

Java calculator :

In that tutorial we have done only addition of two numbers here we will provide all the major four arthematic operators.You may even add additional operators.

  1. Addition
  2. Substraction
  3. Multiply
  4. Divide

Declare four variables for user inputs, result, and selection user option for operation type.

public static int a;
public static int b;
public static int option;
public static int result;

 

initialize a Scanner class object for accepting user input

Scanner scan = new Scanner(System.in);

 

Accept two numbers

System.out.println("Enter first number");

a = scan.nextInt();

System.out.println("Enter second number");

b = scan.nextInt();

 

Ask user the operation to be performed

System.out.println(" 1) Addition \n 2) Substraction \n 3) Multiply \n 4) Divide");

option = scan.nextInt();

 

now we know the user operation to be performed using if condition

if (option == 1)
    result = a + b;
else if (option == 2)
    result = a - b;
else if (option == 3)
    result = a * b;
else if (option == 4)
    result = a / b;

 

Now print output after calculation

 

Scanner scan = new Scanner(System.in);

System.out.println("Enter first number");

a = scan.nextInt();

System.out.println("Enter second number");

b = scan.nextInt();

System.out.println(" 1) Addition \n 2) Substraction \n 3) Multiply \n 4) Divide");

option = scan.nextInt();

if (option == 1)
    result = a + b;
else if (option == 2)
    result = a - b;
else if (option == 3)
    result = a * b;
else if (option == 4)
    result = a / b;

System.out.println("result :" + result);

 

If you have any query on java calculator let us know in comment section below.

For more interesting tutorial like, share this tutorial.

abhishek:
Related Post

This website uses cookies.