Saturday, October 25, 2025
HomeLanguagesJavaBasic Calculator Program in Java Using if/else Statements

Basic Calculator Program in Java Using if/else Statements

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
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS