Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Calculator Program in Java

Last Updated on June 6, 2023 by Mayank Dham

A calculator program in Java allows performing arithmetic operations like addition, subtraction, multiplication, division, and modulo on two numbers. This article explores two methods: If-Else and Switch-Case, to implement the calculator program. It provides code examples and explanations for each method. The time and space complexity of the program are analyzed, with both being constant (O(1)). By understanding the purpose, methods, and implementation details, readers can enhance their understanding of algorithmic thinking and decision-making structures in Java programming.

Purpose of Calculator Program in Java

A calculator program can be put to use to perform arithmetic operations like addition, subtraction, division, multiplication, and modulo of two numbers by getting user input and giving the output as the result of the computation.

Methods to solve:

1. If-Else
2. Switch-Case

Dry Run of Calculator Program in Java

Suppose we have two operands, a and b, and we have to perform the following arithmetic operations discussed, namely, addition, subtraction, multiply, divide and modulo, hence we assign 5 to a while 3 to b, tracing out for each operation,

Addition can be stated as, a+b which results in 5+3 = 8.

Subtraction can be stated as, a-b which results in 5-3 = 2.

Multiplication can be stated as, ab which results in 53 = 12.

Division can be stated as, a/b which results in 5/3 = 1.

Modulo can be stated as, a%b which results in 5%3 = 2.

As suggested above, any of the operations will be performed, with the result stored in a variable. On printing the result, we end the program successfully.

Algorithm for Calculator Program in Java

Having seen the dry run for a calculator program in java, it just might be clearer to understand the algorithm. Here is a short and concise algorithm learning up to the implementation of code for the calculator program in java.

  1. Take two numbers as user input using the Scanner Class

  2. Take the operation to be performed using the Scanner Class

  3. Use logic ( if-lse or switch-case) to select the operation to perform on the two operands.

  4. Store the computed value in result.

  5. Print the result.

Calculator Code in Java

Now that we have clarity on the concept and logic working under the hood of the calculator program in Java, we will implement the code in two different ways.

Code for Calculator Program in Java

Now that we have clarity on the concept and logic working under the hood for the calculator program in java. We will implement the code in two different methods.

Approach 1 – Using If-Else Method

import java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the first number: ");
        int firstNumber = sc.nextInt();
        System.out.print("Enter the second number: ");
        int secondNumber = sc.nextInt();

        System.out.print("Enter the type of operation you want to perform (+, -, *, /, %): ");
        String operation = sc.next();
        int result = performOperation(firstNumber, secondNumber, operation);
        System.out.println("Your answer is: " + result);
    }

    public static int performOperation(int firstNumber, int secondNumber, String operation)
    {
        int result = 0;
        if (operation.equals("+")) {
            result = firstNumber + secondNumber;
        }
        else if (operation.equals("-")) {
            result = firstNumber - secondNumber;
        }
        else if (operation.equals("*")) {
            result = firstNumber * secondNumber;
        }
        else if (operation.equals("%")) {
            result = firstNumber % secondNumber;
        }
        else if (operation.equals("/")) {
            result = firstNumber / secondNumber;
        }
        else {
            System.out.println("Invalid operation");
        }
        return result;
    }
}

Explanation: Once the inputs are taken, we take the operation as input and pass the three into solver function, wherein each operation is checked for its equality with the operation string with the result assigned and returned. If not, an invalid message with returned value, 0 pops up.

Output:

Enter the first number: 3
Enter the second number: 7
Enter the type of operation you want to perform (+, -, *, /, %): +
Your answer is: 10

Approach 2 – Using Switch Case Method

//Using Switch Case
import java.util.Scanner;
 
public class SimpleCalculator {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
 

        System.out.print("Enter the first number: ");
        int firstNumber = sc.nextInt();
        System.out.print("Enter the second number: ");
        int secondNumber = sc.nextInt();
 

        System.out.print("Enter the type of operation you want to perform (+, -, *, /, %): ");
        String operation = sc.next();
        int result = performOperation(firstNumber, secondNumber, operation);
        System.out.println("Your answer is: " + result);
    }
 
    public static int performOperation(int firstNumber, int secondNumber, String operation)
    {
        int result = 0;
        switch (operation) {
            case "+":
                result = firstNumber + secondNumber;
                break;
            case "-":
                result = firstNumber - secondNumber;
                break;
            case "*":
                result = firstNumber * secondNumber;
                break;
            case "%":
                result = firstNumber % secondNumber;
                break;
            case "/":
                result = firstNumber / secondNumber;
                break;
            default:
                System.out.println("Invalid operation");
                break;
        }
        return result;
    }
}

Explanation: : Once the inputs are taken, we take the operation as input and pass the three into the solver function, wherein the operation is passed inside the switch and the case that satisfies the operation criteria is going to be performed and returned as a result, if not, then the default message will be printed and 0 will be returned.

Output:

Enter the first number: 3
Enter the second number: 7
Enter the type of operation you want to perform (+, -, *, /, %): +
Your answer is: 10

Analysis of Calculator Program in Java

Coming to the cost of the calculator program in Java, first, let us discuss the time complexity. As no such container of elements is iterated, the program takes constant time complexity in this manner. Hence, the time complexity is O(1) for the calculator program in java.

As for the space, complexity is concerned, no extra auxiliary space is consumed with the only storage used being for a couple of integer operands and an operation string. Thus, the space complexity for the calculator program is constant as well. The space complexity can be denoted as O(1).

Conclusion
In conclusion, the calculator program in Java serves as a valuable tool for performing basic arithmetic operations on two numbers. This article explored two popular methods, If-Else and Switch-Case, for implementing the calculator program. By providing code examples and explanations, readers gained insights into the logic and structure of each method.Furthermore, the analysis of time and space complexity revealed that the calculator program operates with constant complexity, making it efficient for calculations. By understanding the purpose, methods, and implementation details of the calculator program, readers have enhanced their understanding of algorithmic thinking and decision-making structures in Java programming. This knowledge can be applied to various scenarios, empowering programmers to build more sophisticated applications and solve complex mathematical problems.

Frequently Asked Questions (FAQs)

Q1.What is the advantage of using the If-Else method over the Switch-Case method in the calculator program?
The advantage of using the If-Else method is that it provides more flexibility and allows for complex conditional logic. It can handle a wide range of conditions and is suitable for scenarios where multiple conditions need to be checked.

Q2.Can I add more arithmetic operations to the calculator program?
Absolutely! The calculator program can be expanded to include additional arithmetic operations by extending the If-Else or Switch-Case statements. Simply add the new operation as a condition and implement the corresponding calculation logic.

Q3. How can I handle division by zero in the calculator program?
Division by zero is an error condition that needs to be handled in the calculator program. Before performing division, you can add a check to ensure that the second operand is not zero. If it is zero, you can display an appropriate error message to the user and prevent the calculation.

Q4. Is it possible to make the calculator program more user-friendly by incorporating error handling for invalid input?
Yes, it is definitely recommended to incorporate error handling for invalid input. You can use try-catch blocks to catch exceptions and handle incorrect user input gracefully. By implementing proper validation and error messages, you can enhance the user experience and prevent unexpected program crashes.

Q5. Can the calculator program be modified to handle floating-point numbers?
Certainly! The calculator program can be modified to handle floating-point numbers by changing the data type of the operands and using appropriate floating-point arithmetic operations such as addition, subtraction, multiplication, and division. By accommodating floating-point numbers, the program becomes more versatile and capable of performing calculations with decimal values.

Leave a Reply

Your email address will not be published. Required fields are marked *