Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:

>> GET ACCESS NOW

1. Overview

In this tutorial, we'll implement a Basic Calculator in Java supporting addition, subtraction, multiplication and division operations.

We'll also take the operator and operands as inputs and process the calculations based on them.

2. Basic Setup

First, let's show some information about the calculator:

System.out.println("---------------------------------- \n" +
  "Welcome to Basic Calculator \n" +
  "----------------------------------");
System.out.println("Following operations are supported : \n" +
  "1. Addition (+) \n" +
  "2. Subtraction (-) \n" +
  "3. Multiplication (*) \n" +
  "4. Division (/) \n");

Now, let's use java.util.Scanner to take the user inputs:

Scanner scanner = new Scanner(System.in);

System.out.println("Enter an operator: (+ OR - OR * OR /) ");
char operation = scanner.next().charAt(0);

System.out.println("Enter the first number: ");
double num1 = scanner.nextDouble();

System.out.println("Enter the second number: ");
double num2 = scanner.nextDouble();

As we are taking inputs into the system, we need to validate them. For example, if the operator is not +, -, * or /, then our calculator should call out the bad input. Similarly, if we enter the second number as 0 for division operation, the results will not be good.

So, let's implement these validations.

First, let's focus on the situation when the operator is invalid:

if (!(operation == '+' || operation == '-' || operation == '*' || operation == '/')) {
    System.err.println("Invalid Operator. Please use only + or - or * or /");
}

Then we can show errors for invalid operations:

if (operation == '/' && num2 == 0.0) {
    System.err.println("The second number cannot be zero for division operation.");
}

The user inputs are first validated. After that, the calculation result will be displayed as:

<number1> <operation> <number2> = <result>

3. Processing Calculations

Firstly, we can use an if-else construct to process calculations

if (operation == '+') {
    System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
} else if (operation == '-') {
    System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
} else if (operation == '*') {
    System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
} else if (operation == '/') {
    System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
} else {
    System.err.println("Invalid Operator Specified.");
}

Similarly, we can use a Java switch statement:

switch (operation) {
    case '+':
        System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
        break;
    case '-':
        System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
        break;
    case '*':
        System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
        break;
    case '/':
        System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
        break;
    default:
        System.err.println("Invalid Operator Specified.");
        break;
}

We can use a variable to store the calculation results. As a result, it can be printed at the end. In this case, System.out.println will be used only once.

Also, the maximum range for the calculations is 2147483647. Consequently, if we exceed it, we'll overflow from an int data type. Therefore, it should be stored in a variable of a bigger data type, for example, a double data type.

4. Conclusion

In this tutorial, we implemented a Basic Calculator in Java, using two different constructs. We also made sure the inputs are validated before processing them further.

As always, the code is available over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!