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Â
- Take two numbers and the operator as inputs from the user using the Scanner class..
- Use nested if/else statements to write the logic for the operations
- Initialize a new integer which will store the answer initially as 0
- Print the answer
The code in Java
Java
| importjava.util.Scanner;  publicclassCalculator {    publicstaticvoidmain(String[] args)    {        Scanner sc = newScanner(System.in);          // taking input from the user using the Scanner        // class        System.out.print(            "Enter the first and the Second number - ");        inta = sc.nextInt();        intb = sc.nextInt();          // selecting the operand for the calculations        System.out.print(            "Choose and Enter the type of operation you want to perform (+, -, *, /, %) - ");        charop = sc.next().charAt(0);        solve(a, b, op);    }    publicstaticintsolve(inta, intb, charop)    {        intans = 0;        // addition        if(op == '+') {            ans = a + b;            // subtraction        }        elseif(op == '-') {            ans = a - b;            // multiplication        }        elseif(op == '*') {            ans = a * b;            // modulo        }        elseif(op == '%') {            ans = a % b;            // division        }        elseif(op == '/') {            ans = a / b;        }          // printing the final result        System.out.println("Your answer is - "+ ans);        returnans;    }} | 
Output:
Enter the two numbers - 2, 2 Choose and Enter the type of operation you want to perform (+, -, *, /, %) - + Your Answer is = 4


 
                                    







