Creating a Calculator App in Java


Introduction

Building a calculator application is a classic project for Java developers. In this guide, we'll walk you through the process of creating a simple command-line calculator app in Java. You'll learn how to take user input, perform basic mathematical operations, and display the results. Let's get started.


Prerequisites

Before you start building the calculator app, make sure you have the following prerequisites:


  • Java Development Kit (JDK) installed on your computer.
  • An integrated development environment (IDE) for Java, such as IntelliJ IDEA or Eclipse.
  • Basic knowledge of Java programming.

Creating the Calculator App

We'll create a simple text-based calculator that can perform addition, subtraction, multiplication, and division. Users will enter mathematical expressions, and the program will evaluate and display the results.


Java Code:

import java.util.Scanner;
public class CalculatorApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Simple Calculator App");
System.out.println("Supported Operations: +, -, *, /");
System.out.print("Enter an expression (e.g., 2 + 3): ");
String input = scanner.nextLine();
try {
String[] parts = input.split(" ");
if (parts.length != 3) {
throw new IllegalArgumentException("Invalid input");
}
double num1 = Double.parseDouble(parts[0]);
double num2 = Double.parseDouble(parts[2]);
char operator = parts[1].charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
throw new ArithmeticException("Division by zero");
}
result = num1 / num2;
break;
default:
throw new IllegalArgumentException("Invalid operator");
}
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Invalid number format");
} catch (IllegalArgumentException | ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Running the Calculator App

To run the calculator app, follow these steps:


  1. Compile and run the CalculatorApp class in your Java IDE.
  2. Enter a mathematical expression in the format "number operator number" (e.g., "2 + 3") and press Enter.
  3. The app will evaluate the expression and display the result or an error message if the input is invalid.

Conclusion

Creating a simple calculator app in Java is a great way to practice basic input/output and conditional statements. You can expand on this project by adding more features, supporting additional operations, or creating a graphical user interface (GUI) for the calculator. It's a fun and educational project for Java beginners.