Here's a Java program that creates a simple calculator with basic arithmetic operations (addition, subtraction, multiplication, division) using both console-based and GUI (Swing) implementations. I'll provide both versions so you can choose the one that suits your needs.
1. Console-Based Calculator
This version runs in the console and uses a menu-driven approach.
import java.util.Scanner;
public class ConsoleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2, result;
char operator;
while (true) {
// Display menu
System.out.println("\nSimple Calculator");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.println("5. Exit");
System.out.print("Choose an operation (1-5): ");
int choice = scanner.nextInt();
// Exit condition
if (choice == 5) {
System.out.println("Calculator closing...");
break;
}
// Validate choice
if (choice < 1 || choice > 5) {
System.out.println("Invalid choice! Please select a valid option.");
continue;
}
// Input numbers
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
// Perform calculation based on choice
switch (choice) {
case 1: // Addition
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case 2: // Subtraction
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case 3: // Multiplication
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case 4: // Division
if (num2 == 0) {
System.out.println("Error! Division by zero is not allowed.");
} else {
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
}
break;
}
}
scanner.close();
}
}
Explanation of Console-Based Calculator:
- The program uses a
Scanner to take user input.
- A menu is displayed to choose the operation.
- The program handles basic arithmetic operations and includes error handling for division by zero.
- The loop continues until the user chooses to exit (option 5).
2. GUI-Based Calculator (Using Swing)
This version creates a graphical user interface (GUI) calculator using Java Swing.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUICalculator extends JFrame {
private JTextField displayField;
private double result = 0;
private String lastCommand = "=";
private boolean start = true;
public GUICalculator() {
// Set up the display field
displayField = new JTextField("0");
displayField.setEditable(false);
displayField.setHorizontalAlignment(JTextField.RIGHT);
// Create button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));
// Add buttons
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
buttonPanel.add(button);
if (Character.isDigit(label.charAt(0)) || label.equals(".")) {
button.addActionListener(new NumberListener());
} else {
button.addActionListener(new OperatorListener());
}
}
// Add clear button
JButton clearButton = new JButton("C");
clearButton.addActionListener(e -> {
start = true;
result = 0;
lastCommand = "=";
displayField.setText("0");
});
// Layout setup
setLayout(new BorderLayout());
add(displayField, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
add(clearButton, BorderLayout.SOUTH);
// Frame setup
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
setLocationRelativeTo(null); // Center the window
}
// Listener for number buttons and decimal point
private class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
displayField.setText(input);
start = false;
} else {
displayField.setText(displayField.getText() + input);
}
}
}
// Listener for operator buttons
private class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (start) {
if (command.equals("-")) {
displayField.setText(command);
start = false;
} else {
lastCommand = command;
}
} else {
calculate(Double.parseDouble(displayField.getText()));
lastCommand = command;
start = true;
}
}
}
// Perform the calculation
public void calculate(double x) {
switch (lastCommand) {
case "+":
result += x;
break;
case "-":
result -= x;
break;
case "*":
result *= x;
break;
case "/":
if (x == 0) {
JOptionPane.showMessageDialog(this, "Error! Division by zero.");
return;
}
result /= x;
break;
case "=":
result = x;
break;
}
displayField.setText("" + result);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GUICalculator calc = new GUICalculator();
calc.setVisible(true);
});
}
}
Explanation of GUI-Based Calculator:
- Swing Components: The calculator uses
JFrame for the window, JTextField for the display, and JButton for the buttons.
- Layout: A
BorderLayout is used to organize the display at the top, buttons in the center, and a clear button at the bottom. The buttons are arranged in a 4x4 grid using GridLayout.
- Event Handling: Two
ActionListener classes (NumberListener and OperatorListener) handle number input and operator actions, respectively.
- Functionality:
- Numbers and the decimal point are appended to the display.
- Operators trigger calculations based on the previous operator and the current number.
- The "C" button clears the calculator state.
- Division by zero is handled with an error message.
- Main Method: The
SwingUtilities.invokeLater ensures the GUI is created on the Event Dispatch Thread (EDT), which is a best practice for Swing applications.
How to Run the Programs
-
Console-Based Calculator:
-
GUI-Based Calculator:
Enhancements You Can Add
-
Console-Based:
- Add more operations (e.g., power, square root, modulus).
- Implement memory functions (M+, M-, MR, MC).
- Add input validation for non-numeric inputs.
-
GUI-Based:
- Add more buttons for advanced operations (e.g., sin, cos, log).
- Implement keyboard input support.
- Add a history feature to display previous calculations.
- Improve the UI with colors, fonts, or a modern look.
Let me know if you need help with any enhancements or have questions!