Scanner
class in Java is used to effectively capture numbers and operators directly from the user's console input.switch
statement to cleanly manage different arithmetic operations (+, -, *, /) based on user choice.Creating a basic calculator is a classic beginner project in Java. It introduces fundamental programming concepts like handling user input, using variables, implementing conditional logic, and performing arithmetic operations. This guide will walk you through building a console-based calculator that takes two numbers and an operator from the user and displays the result.
While this guide focuses on a console calculator, Java can also create graphical interfaces (GUIs) as shown above.
Below is the complete Java code for a simple calculator. It prompts the user for two numbers and an arithmetic operator, calculates the result, and handles potential errors like division by zero.
import java.util.Scanner; // Import the Scanner class for reading user input
import java.util.InputMismatchException; // Import for handling non-numeric input
public class SimpleCalculator {
public static void main(String[] args) {
// Declare variables to hold the numbers, operator, and result
double num1 = 0, num2 = 0, result;
char operator;
boolean validInput; // Flag for input validation loop
// Create a Scanner object to read input from the console
Scanner scanner = new Scanner(System.in);
System.out.println("--- Simple Java Calculator ---");
// Input loop for the first number with error handling
validInput = false;
while (!validInput) {
System.out.print("Enter the first number: ");
try {
num1 = scanner.nextDouble(); // Read the first number
validInput = true; // Input is valid, exit loop
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a numeric value.");
scanner.next(); // Consume the invalid input to prevent infinite loop
}
}
// Input for the operator
System.out.print("Enter an operator (+, -, *, /): ");
operator = scanner.next().charAt(0); // Read the operator character
// Input loop for the second number with error handling
validInput = false;
while (!validInput) {
System.out.print("Enter the second number: ");
try {
num2 = scanner.nextDouble(); // Read the second number
validInput = true; // Input is valid, exit loop
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a numeric value.");
scanner.next(); // Consume the invalid input
}
}
// Use a switch statement to determine which operation to perform
switch (operator) {
case '+':
result = num1 + num2;
// Display the result formatted to two decimal places
System.out.printf("%.2f + %.2f = %.2f%n", num1, num2, result);
break;
case '-':
result = num1 - num2;
System.out.printf("%.2f - %.2f = %.2f%n", num1, num2, result);
break;
case '*':
result = num1 * num2;
System.out.printf("%.2f * %.2f = %.2f%n", num1, num2, result);
break;
case '/':
// Check for division by zero before performing the calculation
if (num2 != 0) {
result = num1 / num2;
System.out.printf("%.2f / %.2f = %.2f%n", num1, num2, result);
} else {
// Print an error message if division by zero is attempted
System.out.println("Error! Division by zero is not allowed.");
}
break;
// Handle cases where the user enters an invalid operator
default:
System.out.println("Error! Invalid operator entered. Please use +, -, *, or /.");
}
// Close the scanner object to release system resources
// It's good practice to close resources you open
scanner.close();
System.out.println("-----------------------------");
}
}
import java.util.Scanner;
brings in the Scanner
class, which is essential for reading input from the console (like keyboard entries). import java.util.InputMismatchException;
is imported to handle cases where the user might enter text instead of a number.
All Java code resides within a class. Here, it's public class SimpleCalculator
. The execution starts in the public static void main(String[] args)
method, the entry point of any Java application.
Variables num1
, num2
(using double
to allow decimal numbers), result
, and operator
(using char
for a single character) are declared to store the user's input and the calculation outcome. A boolean
flag validInput
is used for input validation loops.
Scanner scanner = new Scanner(System.in);
creates an instance of the Scanner
class, configured to read from standard input (System.in), which is typically the keyboard.
System.out.println(...)
and System.out.print(...)
display messages asking the user to enter numbers and an operator.
scanner.nextDouble()
reads the double
numbers entered by the user. This is placed inside a try-catch
block within a while
loop to ensure the user enters a valid number. If non-numeric input is detected (InputMismatchException
), an error message is shown, and the loop continues.
scanner.next().charAt(0)
reads the next token (string) entered and takes its first character as the operator.
switch
A switch
statement efficiently handles the different arithmetic operations based on the operator
variable. Each case
corresponds to an operator (+, -, \*, /).
The calculation is performed, and the result is stored in the result
variable.
System.out.printf(...)
is used to display the output formatted neatly to two decimal places.
Inside the division case (case '/'
), an if
condition checks if num2
is zero. Dividing by zero is mathematically undefined and causes errors in programs. If num2
is zero, an error message is displayed; otherwise, the division proceeds.
The default
case in the switch
statement catches any input that doesn't match the valid operators (+, -, \*, /) and informs the user.
scanner.close();
releases the system resources associated with the Scanner
object. It's crucial to close resources like scanners or file streams when they are no longer needed to prevent resource leaks.
To run this Java code:
SimpleCalculator.java
. Ensure the file name exactly matches the class name.javac SimpleCalculator.java
This will create a SimpleCalculator.class
file if there are no compilation errors.
java SimpleCalculator
This mindmap illustrates the key components and flow of the simple Java calculator program, from initialization to displaying the final result.
This radar chart provides a qualitative assessment of the simple console-based Java calculator based on several key software attributes. It highlights its strengths in simplicity and core functionality, while also indicating areas for potential improvement like advanced error handling or user interface design.
The calculator supports the four fundamental arithmetic operations. The table below summarizes how each is implemented in the Java code.
Operator | Symbol | Description | Implementation Detail | Considerations |
---|---|---|---|---|
Addition | + |
Adds the two numbers (num1 and num2 ). |
result = num1 + num2; |
Standard arithmetic addition. Works with integers and doubles. |
Subtraction | - |
Subtracts the second number (num2 ) from the first (num1 ). |
result = num1 - num2; |
Standard arithmetic subtraction. Order matters (num1 - num2 is different from num2 - num1 ). |
Multiplication | * |
Multiplies the two numbers (num1 and num2 ). |
result = num1 * num2; |
Standard arithmetic multiplication. |
Division | / |
Divides the first number (num1 ) by the second (num2 ). |
if (num2 != 0) { result = num1 / num2; } else { // Error } |
Requires a check to prevent division by zero, which is mathematically undefined and causes a runtime error (ArithmeticException if not handled). Using double allows for floating-point results. |
Watching someone build the calculator can be very helpful. This video tutorial provides a visual walkthrough of creating a basic calculator in Java, explaining the concepts as it goes. It covers similar ground to the code presented here, focusing on user input and operations.
This tutorial reinforces the use of the Scanner
for input and demonstrates how to structure the code to handle different calculations, making it a great supplement to reading the code and explanations.
While the provided code creates a functional simple calculator, several enhancements and best practices can be considered for more complex or robust applications:
while
loop around the main logic to allow the user to perform multiple calculations without restarting the program. You could add an option to 'quit' the calculator.try-catch
blocks for various potential runtime exceptions.switch
statement to include additional mathematical operations like modulus (%
), exponentiation (Math.pow()
), square root (Math.sqrt()
), etc.CalculatorLogic
class for calculations, a UserInput
class for handling input).switch
statement.Scanner
class?The Scanner
class (java.util.Scanner
) is the standard and most convenient way in Java to read input from various sources, including the system console (System.in
). It provides methods like nextDouble()
, nextInt()
, next()
, and nextLine()
to parse different data types easily from the input stream, making it ideal for interactive command-line applications like this calculator.
A `switch` statement is often clearer and more readable than multiple nested `if-else if` statements when you need to perform different actions based on the value of a single variable (like the `operator` character here). It directly jumps to the matching `case`, which can sometimes be slightly more efficient. It's particularly well-suited for scenarios with a fixed set of possible values.
The example code uses a `try-catch` block specifically for `InputMismatchException` when reading numbers with `scanner.nextDouble()`. This prevents the program from crashing if the user types text instead of a number. The `while` loop ensures the program keeps asking until valid numeric input is received. You could extend this with more specific error messages or logging if needed.
Yes, absolutely! While this example focuses on a console interface, Java provides libraries like Swing (older) and JavaFX (newer) specifically for building Graphical User Interfaces (GUIs). You would design a window with buttons for numbers and operators, a display field for input and results, and then link the button actions to the calculation logic (similar to the `switch` statement logic used here). Several online tutorials demonstrate building GUI calculators in Java.