calculator using java scanner class

Dynamic Calculator in Java Using Scanner Class (2026 Guide)

Dynamic Calculator in Java Using Scanner Class

In this tutorial, you will build a menu-driven calculator in Java that accepts user input via the Scanner class. The program offers four operations — addition, subtraction, multiplication, and division — and lets the user repeat calculations until they choose to exit.

You will learn how Scanner reads from the keyboard, how switch-case handles menu choices, and how do-while creates a repeatable interaction loop.

What You Will Build

Dynamic calculator in Java using Scanner class

A console-based calculator with:

  • Four arithmetic operations — add, subtract, multiply, divide
  • Menu-driven interface using switch-case
  • Loop that repeats until the user types n
  • User input via Scanner

Complete Java Code

Save this as Cal.java and compile with javac Cal.java:

import java.util.Scanner;

public class Cal {

    void add(int i, int j) {
        System.out.println(i + j);
    }

    void sub(int i, int j) {
        System.out.println(i - j);
    }

    void mul(int i, int j) {
        System.out.println(i * j);
    }

    void div(int i, int j) {
        System.out.println(i / j);
    }

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        Cal c = new Cal();

        String text = "";

        do {
            System.out.println("Press 1 for Add");
            System.out.println("Press 2 for Subtract");
            System.out.println("Press 3 for Multiply");
            System.out.println("Press 4 for Divide");
            System.out.print("Enter your choice: ");

            int choice = s.nextInt();
            int i, j;

            switch (choice) {

                case 1:
                    System.out.print("Enter first number: ");
                    i = s.nextInt();
                    System.out.print("Enter second number: ");
                    j = s.nextInt();
                    c.add(i, j);
                    break;

                case 2:
                    System.out.print("Enter first number: ");
                    i = s.nextInt();
                    System.out.print("Enter second number: ");
                    j = s.nextInt();
                    c.sub(i, j);
                    break;

                case 3:
                    System.out.print("Enter first number: ");
                    i = s.nextInt();
                    System.out.print("Enter second number: ");
                    j = s.nextInt();
                    c.mul(i, j);
                    break;

                case 4:
                    System.out.print("Enter first number: ");
                    i = s.nextInt();
                    System.out.print("Enter second number: ");
                    j = s.nextInt();
                    c.div(i, j);
                    break;

                default:
                    System.out.println("Wrong choice");
            }

            System.out.print("Do you want to continue? (y/n): ");
            text = s.next();

        } while (text.equalsIgnoreCase("y"));

        s.close();
    }
}

Sample Output

Press 1 for Add
Press 2 for Subtract
Press 3 for Multiply
Press 4 for Divide
Enter your choice: 1
Enter first number: 15
Enter second number: 25
40
Do you want to continue? (y/n): y
Press 1 for Add
Press 2 for Subtract
Press 3 for Multiply
Press 4 for Divide
Enter your choice: 4
Enter first number: 100
Enter second number: 5
20
Do you want to continue? (y/n): n

How It Works (Step-by-Step)

  1. Create a Scanner — new Scanner(System.in) opens a stream to read keyboard input.
  2. Create the calculator object — new Cal() gives us access to the add, sub, mul, and div methods.
  3. Enter the do-while loop — the loop runs at least once and continues as long as the user types y.
  4. Display the menu — four System.out.println calls show the available operations.
  5. Read the choice — s.nextInt() reads the menu selection as an integer.
  6. Execute the operation — the switch statement calls the appropriate method based on the user's choice.
  7. Ask to continue — s.next() reads the user's answer and stores it in text.
  8. Check the loop condition — text.equalsIgnoreCase("y") returns true if the user typed y or Y, repeating the loop.
  9. Close the scanner — s.close() releases the input stream.

Improvements & Best Practices

This program works, but a few improvements make it more robust and production-ready:

1. Handle division by zero

void div(int i, int j) {
    if (j == 0) {
        System.out.println("Cannot divide by zero");
        return;
    }
    System.out.println(i / j);
}

2. Use double instead of int for division

With int, 10 / 3 returns 3 (truncated). Use double if you want precise decimal results:

void div(double i, double j) {
    System.out.println(i / j);
}

3. Refactor repeated input code

All four cases read two numbers from the user. Move that logic into a helper method:

private static int[] readTwoNumbers(Scanner s) {
    System.out.print("Enter first number: ");
    int i = s.nextInt();
    System.out.print("Enter second number: ");
    int j = s.nextInt();
    return new int[]{i, j};
}

4. Handle invalid input

If the user types letters instead of a number, nextInt() throws InputMismatchException. Wrap it in a try-catch to handle this gracefully.

5. Method design

The add, sub, mul, and div methods print the result directly. A cleaner design returns the value and lets the caller decide what to do with it:

int add(int i, int j) {
    return i + j;
}

// caller
System.out.println("Result: " + c.add(10, 20));

Frequently Asked Questions

How do I take user input in Java?

Use the Scanner class from the java.util package. Create an instance with new Scanner(System.in), then call nextInt() for integers, nextDouble() for decimals, nextLine() for strings, or next() for words.

What does the nextInt() method do in Java?

nextInt() reads the next integer token from the input source (usually the keyboard) and returns it as an int. It throws InputMismatchException if the input is not a valid integer.

Why does my Java calculator crash when I divide by zero?

Integer division by zero throws ArithmeticException at runtime. To handle this, check if the second operand is zero before dividing, or wrap the division in a try-catch block.

What is the difference between next() and nextLine() in Scanner?

next() reads a single word up to whitespace. nextLine() reads the entire line including spaces, until the user presses Enter. Use nextLine() when you need to read full sentences or handle leftover newline characters.

Should I close the Scanner in Java?

Yes, when you are done using it. Use scanner.close() to release the underlying input stream. This is especially important in long-running applications to avoid resource leaks.

Conclusion

In this tutorial, you built a complete dynamic calculator in Java using the Scanner class. You learned how to read user input, use switch-case for menu handling, and loop with do-while for repeat interactions.

This is a great beginner project because it combines several core Java concepts — classes, methods, conditionals, loops, and input handling — in one place. Try the improvements above to make it production-quality.

Related topics: Java Scanner Class, Java Switch Case, Java do-while Loop, Java Methods, Java Exception Handling, Java Basic Programs

8 comments:

Melinda Mullen said...

cx

Fonts Mania said...
This comment has been removed by the author.
Fonts Mania said...

Hey Man! when you want any font file for future work then choose from this website;

Royalty Free Fonts

Mary Schmitz said...

This is wonderful and quite informative blog I have learnt so many things from here.
ui company number

Anna Rexia said...

They’ve prioritized mutual understanding throughout the engagement.
design agency San Francisco

Ivan Irwin said...

The team delivered excellent products on time or ahead of schedule at great value.
best logo design company

Jamie Mack said...

That’s a nice site you people are carrying out there.
mobile app design agency

Robet John said...

Your articles and blogs are inspirational.
brand design firm