Building a Simple Calculator in Java

Building a Simple Calculator in Java

Hello everyone! Today, we’re diving into a classic beginner project in Java When learning a new programming language, one of the best ways to solidify your understanding is by building small, functional projects. Recently, I created a simple calculator in Java, and it was an excellent exercise in understanding core programming concepts like methods, conditional logic, and error handling. In this article, I’ll walk you through my thought process, the challenges I faced, and the key takeaways from this project.


The Goal

The goal of this project was to create a basic calculator that could perform addition, subtraction, multiplication, and division. Additionally, I wanted to handle edge cases like division by zero and invalid user inputs. The calculator needed to be robust enough to provide meaningful feedback when something went wrong.


The Code Structure

The calculator is implemented as a single Java class named calculator. Here’s a breakdown of its structure:

  1. Main Method: The main method serves as the entry point for the program. It calls the calculatorMethode with different inputs to demonstrate its functionality.

  2. calculatorMethode: This is the core method that takes two numbers and an operation (as a string) and returns the result. It uses a helper function to validate the operation and then delegates the calculation to specific methods like additionFuction, subtractionFuction, etc.

  3. Helper Function: The helperFunction ensures that the operation provided by the user is valid. It checks for null or empty inputs and validates whether the operation is one of the supported ones (+, -, *, /).

  4. Arithmetic Functions: Each arithmetic operation (addition, subtraction, multiplication, and division) is handled by a separate method. These methods perform the calculation and return the result as a string.

  5. Error Handling: The program handles edge cases like division by zero and invalid operations gracefully. For example, if the user tries to divide by zero, the program returns "THE VALUE OF THE OPERATION IS INFINITE" or "THE VALUE OF THE OPERATION IS UNDEFINED" depending on the scenario.


The Code

Here’s the complete Java code for the calculator:

public class Calculator {
    public static void main(String[] args) {
        System.out.println(calculatorMethode(10, 5, "+")); // Output: 15.0
        System.out.println(calculatorMethode(10, 5, "-")); // Output: 5.0
        System.out.println(calculatorMethode(10, 5, "*")); // Output: 50.0
        System.out.println(calculatorMethode(10, 5, "/")); // Output: 2.0
        System.out.println(calculatorMethode(10, 0, "/")); // Output: THE VALUE OF THE OPERATION IS INFINITE
        System.out.println(calculatorMethode(0, 0, "/")); // Output: THE VALUE OF THE OPERATION IS UNDEFINED
        System.out.println(calculatorMethode(10, 5, "%")); // Output: ENTER A VALID OPERATION (+, -, *, /)
    }

    public static final String WRONG_INPUT_ERROR = "ENTER A VALID OPERATION (+, -, *, /)";
    public static final String NO_INPUT_ERROR = "YOU MUST ENTER AN OPERATION (+, -, *, /)";
    public static final String INFINITE_VALUE = "THE VALUE OF THE OPERATION IS INFINITE";
    public static final String UNDEFINED_VALUE = "THE VALUE OF THE OPERATION IS UNDEFINED";

    public static String calculatorMethode(double value1, double value2, String operation) {
        String operator = helperFunction(operation);

        if (operator.equals(NO_INPUT_ERROR)) {
            return NO_INPUT_ERROR;
        } else if (operator.equals(WRONG_INPUT_ERROR)) {
            return WRONG_INPUT_ERROR;
        } else {
            switch (operator) {
                case "+":
                    return additionFuction(value1, value2);
                case "-":
                    return subtractionFuction(value1, value2);
                case "*":
                    return multiplicationFuction(value1, value2);
                case "/":
                    return divitionFuction(value1, value2);
                default:
                    return WRONG_INPUT_ERROR;
            }
        }
    }

    public static String additionFuction(double value1, double value2) {
        double result = value1 + value2;
        return Double.toString(result);
    }

    public static String subtractionFuction(double value1, double value2) {
        double result = value1 - value2;
        return Double.toString(result);
    }

    public static String multiplicationFuction(double value1, double value2) {
        double result = value1 * value2;
        return Double.toString(result);
    }

    public static String divitionFuction(double value1, double value2) {
        if (value1 == 0 && value2 == 0) {
            return UNDEFINED_VALUE;
        } else if (value2 == 0) {
            return INFINITE_VALUE;
        } else {
            double result = value1 / value2;
            return Double.toString(result);
        }
    }

    public static String helperFunction(String operation) {
        if (operation == null || operation.trim().isEmpty()) {
            return NO_INPUT_ERROR;
        } else if (operation.equals("+") || operation.equals("-") || operation.equals("*") || operation.equals("/")) {
            return operation;
        } else {
            return WRONG_INPUT_ERROR;
        }
    }
}

Key Learnings

  1. Modularity: Breaking down the problem into smaller, reusable methods made the code easier to read, debug, and maintain. For example, separating the validation logic (helperFunction) from the calculation logic made the code more organized.

  2. Error Handling: Handling edge cases is crucial in building robust applications. By anticipating potential issues (like invalid inputs or division by zero), I was able to make the calculator more user-friendly.

  3. Switch Statements: Using a switch statement to handle different operations made the code cleaner and more efficient compared to multiple if-else statements.

  4. String Comparison: I learned the importance of using .equals() for string comparison in Java instead of ==, which checks for reference equality.

  5. Code Readability: Using meaningful variable names and constants (like WRONG_INPUT_ERROR and INFINITE_VALUE) improved the readability of the code and made it easier to understand.


Challenges Faced

  • Division by Zero: Handling division by zero was tricky. I had to account for two scenarios: when the numerator is zero (resulting in an undefined value) and when the denominator is zero (resulting in infinity).

  • Input Validation: Ensuring that the user inputs a valid operation required careful validation. The helperFunction played a crucial role in this.


Conclusion

Building this simple calculator was a great learning experience. It helped me understand the importance of modularity, error handling, and clean code practices. While the calculator is basic, it lays the foundation for more complex projects in the future. If you’re learning Java, I highly recommend starting with small projects like this to build your confidence and deepen your understanding of the language.

Feel free to try out the code and experiment with it. You can find the full code above. Happy coding!


Your Turn!
Now it’s your turn to try implementing this calculator. Start with the code provided, then challenge yourself to add more features, like handling more operations or creating a user interface. Let me know if you have further questions or need additional clarification! 😊