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

In this article, we will study what is told to be the building block of programming knowledge, the Calculator. This article focuses on the concepts and features of the calculator, along with the dry run, the algorithm and the code for the calculator program in java. Further, the analysis of the program is also mentioned.

By the end of the article, the reader can have clarity on how the operators and operands work. Moreover, the code will be implemented in two methods i.e. Switch-Case and If-else

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.

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 solver function, wherein the operation is passed inside switch and the case that satisfies the operation criteria is going to be performed and returned as result, if not then 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 this article, we studied how the calculator program actually works, with further sections of this article on calculator program in java enunciating the dry run, algorithm, and code and with analysis of code, we bind up with this article on calculator program in java.

We expect you liked this article on calculator program in java. Hope to see you again at PrepBytes with another informative and insightful article.

Other Java Programs

Java Program to Add Two Numbers
Java Program to Check Prime Number
Java Program to Check Whether a Number is a Palindrome or Not
Java Program to Find the Factorial of a Number
Java Program to Reverse a Number
Java Program to search an element in a Linked List
Program to convert ArrayList to LinkedList in Java
Java Program to Reverse a linked list
Java Program to search an element in a Linked List
Anagram Program in Java
Inheritance Program in Java
Even Odd Program in Java
Hello World Program in Java
If else Program in Java
Binary Search Program in Java
Linear Search Program in Java
Menu Driven Program in Java
Package Program in Java
Leap Year Program in Java
Array Programs in Java
Linked List Program in Java
String Programs in Java
Star Program in Java
Number Pattern Program in Java
For Loop Program In Java
Pattern Program in Java
String Palindrome Program in Java
Thread Program in JAVA
Java Scanner Program
While Loop Program in Java
Bubble Sort Program in Java
Fibonacci Series Program in Java

Leave a Reply

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