Open In App

Basic Calculator Program in Java Using if/else Statements

Improve
Improve
Like Article
Like
Save
Share
Report

We will be creating a basic calculator in java using the nested if/else statements which can perform operations like addition, subtraction, multiplication, division, and modulo of any two numbers. We will be defining the numbers as an integer but if you want the decimal side of numbers as well feel free to initiate them as double or float. Let’s see what our calculator will look like – 

Enter the two numbers - 2, 2
Choose and Enter the type of operation you want to perform (+, -, *, /, %)  - +
Your Answer is = 4

Algorithm 

  1. Take two numbers and the operator as inputs from the user using the Scanner class..
  2. Use nested if/else statements to write the logic for the operations
  3. Initialize a new integer which will store the answer initially as 0
  4. Print the answer

The code in Java

Java




import java.util.Scanner;
 
public class Calculator {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
 
        // taking input from the user using the Scanner
        // class
        System.out.print(
            "Enter the first and the Second number - ");
        int a = sc.nextInt();
        int b = sc.nextInt();
 
        // selecting the operand for the calculations
        System.out.print(
            "Choose and Enter the type of operation you want to perform (+, -, *, /, %) - ");
        char op = sc.next().charAt(0);
        solve(a, b, op);
    }
    public static int solve(int a, int b, char op)
    {
        int ans = 0;
        // addition
        if (op == '+') {
            ans = a + b;
            // subtraction
        }
        else if (op == '-') {
            ans = a - b;
            // multiplication
        }
        else if (op == '*') {
            ans = a * b;
            // modulo
        }
        else if (op == '%') {
            ans = a % b;
            // division
        }
        else if (op == '/') {
            ans = a / b;
        }
 
        // printing the final result
        System.out.println("Your answer is - " + ans);
        return ans;
    }
}


Output:

Enter the two numbers - 2, 2
Choose and Enter the type of operation you want to perform (+, -, *, /, %)  - +
Your Answer is = 4


Last Updated : 02 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads