Java Console Calculator Tutorial
This tutorial will guide you through building a simple console calculator in Java. We’ll cover the basics of creating a Java program, using arithmetic operators, taking user input, and displaying results. This is designed for beginners, so we’ll focus on practical code examples and clear explanations.
Example 1: Basic Addition
Let’s start with a very simple calculator that performs addition. This example will take two numbers as input from the user and print their sum.
// Simple Addition Calculator
import java.util.Scanner;
public class SimpleAddition {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
double sum = num1 + num2;
System.out.println("The sum is: " + sum);
scanner.close();
}
}
Explanation:
- import java.util.Scanner;: This line imports the `Scanner` class, which allows us to read input from the console.
- public class SimpleAddition {: This declares a class named `SimpleAddition`. All Java code must reside within a class.
- public static void main(String[] args) {: This is the main method, the entry point of our program.
- Scanner scanner = new Scanner(System.in);: This creates a `Scanner` object named `scanner` and associates it with the standard input stream (`System.in`), which is the console.
- System.out.print(“Enter the first number: “);: This line prints a prompt to the console asking the user to enter the first number.
- double num1 = scanner.nextDouble();: This line reads a double (a floating-point number) from the console and stores it in the variable `num1`. Using `double` allows us to handle decimal numbers.
- System.out.print(“Enter the second number: “);: Similar to the previous line, this prompts the user for the second number.
- double num2 = scanner.nextDouble();: Reads the second number (as a double) and stores it in `num2`.
- double sum = num1 + num2;: This line performs the addition operation and stores the result in the `sum` variable.
- System.out.println(“The sum is: ” + sum);: This line prints the calculated sum to the console.
- scanner.close();: This line closes the `Scanner` object, releasing the resources it was using. It’s good practice to always close scanners when you’re finished with them.
Common Mistakes:
- Forgetting to close the scanner: If you don’t close the scanner, it can cause resource leaks, especially in larger applications.
- Incorrect data type: Using `int` instead of `double` can lead to truncation of decimal numbers.
Output:
Enter the first number: 10
Enter the second number: 5
The sum is: 15.0
Example 2: Implementing Subtraction, Multiplication, and Division
Now, let’s extend our calculator to perform subtraction, multiplication, and division as well. We’ll maintain the input and output structure from the previous example.
// Calculator with Multiple Operations
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.println("Addition: " + (num1 + num2));
System.out.println("Subtraction: " + (num1 - num2));
System.out.println("Multiplication: " + (num1 num2));
System.out.println("Division: " + (num1 / num2));
scanner.close();
}
}
Explanation:
- This code is similar to the previous example, but it now performs all four basic arithmetic operations.
- We use parentheses to explicitly specify the order of operations.
- The results of each operation are printed to the console with descriptive labels.
Output:
Enter the first number: 10
Enter the second number: 2
Addition: 12.0
Subtraction: 8.0
Multiplication: 20.0
Division: 5.0
Example 3: Handling Potential Errors (Division by Zero)
A crucial aspect of writing robust code is handling potential errors. In this case, we need to handle the situation where the user attempts to divide by zero, which would cause a runtime error. We’ll use a `try-catch` block to gracefully handle this scenario.
// Calculator with Error Handling
import java.util.Scanner;
public class CalculatorWithErrorHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
try {
if (num2 == 0) {
System.out.println("Error: Division by zero is not allowed.");
} else {
System.out.println("Addition: " + (num1 + num2));
System.out.println("Subtraction: " + (num1 - num2));
System.out.println("Multiplication: " + (num1 num2));
System.out.println("Division: " + (num1 / num2));
}
} catch (ArithmeticException e) {
System.out.println("An error occurred during calculation: " + e.getMessage());
} finally {
scanner.close();
}
}
}
Explanation:
- try { … }: This block contains the code that might throw an exception (in this case, an `ArithmeticException` if we try to divide by zero).
- if (num2 == 0) { … }: This checks if the second number is zero before performing the division. If it is, an error message is printed.
- catch (ArithmeticException e) { … }: This block catches the `ArithmeticException` if it occurs within the `try` block. The `e` variable holds information about the exception.
- finally { … }: This block always executes, regardless of whether an exception occurred or not. We use it here to close the scanner, ensuring resources are released.
Output (when dividing by zero):
Enter the first number: 10
Enter the second number: 0
Error: Division by zero is not allowed.
Output (when dividing by a non-zero number):
Enter the first number: 10
Enter the second number: 2
Addition: 12.0
Subtraction: 8.0
Multiplication: 20.0
Division: 5.0



Leave a Reply