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);

java calculator

 

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

For more interesting tutorial like, share this tutorial.

Show Buttons
Hide Buttons
Read previous post:
Java Simple Calculator | Java example

[et_pb_section admin_label="section"][et_pb_row admin_label="row"][et_pb_column type="4_4"][et_pb_text admin_label="Text" background_layout="light" text_orientation="left" use_border_color="off" border_color="#ffffff" border_style="solid"] Java simple calculator : We now have learnt how to...

Close