Create a Simple Java Calculator with GUI (Swing)

Simple Java Calculator: Step-by-Step Guide for BeginnersA calculator is one of the classic beginner projects in programming: it’s small enough to complete in a single sitting, yet large enough to teach fundamental concepts like variables, control flow, user input, and basic error handling. This guide walks you through building a simple Java calculator — first a console-based version, then a GUI version using Swing. Along the way you’ll learn how to structure code, handle invalid input, and extend functionality.


What you’ll learn

  • How to set up a Java project and run programs from the command line or an IDE.
  • Implementing arithmetic operations (addition, subtraction, multiplication, division).
  • Reading and validating user input.
  • Structuring code into methods for clarity and reuse.
  • Simple error handling (e.g., division by zero, invalid numbers).
  • (Optional) Building a basic graphical user interface (GUI) with Swing.

Prerequisites

  • Java Development Kit (JDK) 11 or later installed.
  • Basic knowledge of Java syntax: variables, methods, classes, conditionals, loops.
  • A code editor or IDE (IntelliJ IDEA, Eclipse, VS Code with Java extensions, or even a text editor and the terminal).

Part 1 — Console-based Simple Java Calculator

This console calculator handles four basic operations: +, -, *, /. It shows how to request input, parse numbers, and loop until the user chooses to exit.

Features

  • Read two operands and an operator from the user.
  • Validate numeric input.
  • Prevent division by zero.
  • Allow continued calculations until the user quits.

Code (Console Calculator)

import java.util.Scanner; public class SimpleCalculator {     private static final Scanner scanner = new Scanner(System.in);     public static void main(String[] args) {         System.out.println("Simple Java Calculator");         boolean running = true;         while (running) {             double a = readDouble("Enter first number (or type 'q' to quit): ");             double b = readDouble("Enter second number (or type 'q' to quit): ");             char op = readOperator("Enter operator (+, -, *, /): ");             try {                 double result = calculate(a, b, op);                 System.out.printf("Result: %s %c %s = %s%n", a, op, b, result);             } catch (ArithmeticException ex) {                 System.out.println("Error: " + ex.getMessage());             }             System.out.print("Do another calculation? (y/n): ");             String again = scanner.next().trim().toLowerCase();             if (!again.equals("y") && !again.equals("yes")) {                 running = false;             }         }         System.out.println("Goodbye!");     }     private static double readDouble(String prompt) {         while (true) {             System.out.print(prompt);             String input = scanner.next().trim();             if (input.equalsIgnoreCase("q") || input.equalsIgnoreCase("quit")) {                 System.out.println("Exiting...");                 System.exit(0);             }             try {                 return Double.parseDouble(input);             } catch (NumberFormatException ex) {                 System.out.println("Invalid number. Please try again.");             }         }     }     private static char readOperator(String prompt) {         while (true) {             System.out.print(prompt);             String input = scanner.next().trim();             if (input.length() == 1) {                 char c = input.charAt(0);                 if (c == '+' || c == '-' || c == '*' || c == '/') {                     return c;                 }             }             System.out.println("Invalid operator. Enter one of: + - * /");         }     }     private static double calculate(double a, double b, char op) {         switch (op) {             case '+': return a + b;             case '-': return a - b;             case '*': return a * b;             case '/':                 if (b == 0) throw new ArithmeticException("Division by zero is not allowed.");                 return a / b;             default:                 throw new IllegalArgumentException("Unsupported operator: " + op);         }     } } 

How it works (brief)

  • readDouble prompts the user and parses input as double; typing “q” quits the program.
  • readOperator enforces a single character operator and reprompts on invalid input.
  • calculate performs the operation and throws a clear exception for division by zero.
  • The main loop repeats until the user declines.

Part 2 — Adding More Functionality

Once the basic calculator works, you can extend it:

  • Add support for parentheses and operator precedence by implementing an expression parser (shunting-yard algorithm) or using an existing library.
  • Add more functions: modulus %, exponentiation (^ or Math.pow), square-root (Math.sqrt), trigonometric functions.
  • Keep a history of calculations in a list and allow the user to review past results.
  • Support multiple-operand input like “2 + 3 * 4” with correct precedence.
  • Add command-line arguments so users can pass expressions to evaluate directly.

Part 3 — GUI Calculator with Swing (simple)

For a visual, clickable calculator, Swing is lightweight and included with the JDK. The example below creates a simple calculator window with digit buttons, basic operators, and a display.

Code (Swing Calculator)

import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class SimpleGUICalculator extends JFrame {     private final JTextField display = new JTextField();     private double currentValue = 0;     private String currentOp = "";     private boolean startNewNumber = true;     public SimpleGUICalculator() {         super("Simple Java Calculator");         setSize(300, 400);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setLayout(new BorderLayout());         display.setEditable(false);         display.setHorizontalAlignment(SwingConstants.RIGHT);         display.setFont(new Font("Arial", Font.PLAIN, 24));         add(display, BorderLayout.NORTH);         JPanel panel = new JPanel();         panel.setLayout(new GridLayout(4, 4, 5, 5));         String[] buttons = {             "7", "8", "9", "/",             "4", "5", "6", "*",             "1", "2", "3", "-",             "0", ".", "=", "+"         };         for (String text : buttons) {             JButton btn = new JButton(text);             btn.setFont(new Font("Arial", Font.BOLD, 18));             btn.addActionListener(new ButtonListener());             panel.add(btn);         }         add(panel, BorderLayout.CENTER);     }     private class ButtonListener implements ActionListener {         public void actionPerformed(ActionEvent e) {             String cmd = e.getActionCommand();             if ("0123456789.".contains(cmd)) {                 if (startNewNumber) {                     display.setText(cmd.equals(".") ? "0." : cmd);                     startNewNumber = false;                 } else {                     display.setText(display.getText() + cmd);                 }             } else if ("+-*/".contains(cmd)) {                 computePending();                 currentOp = cmd;                 startNewNumber = true;             } else if ("=".equals(cmd)) {                 computePending();                 currentOp = "";                 startNewNumber = true;             }         }         private void computePending() {             try {                 double value = Double.parseDouble(display.getText());                 if (currentOp.isEmpty()) {                     currentValue = value;                 } else {                     switch (currentOp) {                         case "+": currentValue += value; break;                         case "-": currentValue -= value; break;                         case "*": currentValue *= value; break;                         case "/":                             if (value == 0) {                                 JOptionPane.showMessageDialog(SimpleGUICalculator.this,                                         "Cannot divide by zero", "Error", JOptionPane.ERROR_MESSAGE);                                 return;                             }                             currentValue /= value; break;                     }                 }                 display.setText(Double.toString(currentValue));             } catch (NumberFormatException ex) {                 display.setText("Error");             }         }     }     public static void main(String[] args) {         SwingUtilities.invokeLater(() -> {             SimpleGUICalculator calc = new SimpleGUICalculator();             calc.setVisible(true);         });     } } 

Tips for Beginners

  • Start small: get the console version working before attempting a GUI.
  • Keep methods small and focused — one task per method.
  • Use meaningful variable/method names like calculate, readDouble, computePending.
  • Test edge cases: zero division, very large/small numbers, invalid input.
  • Use an IDE debugger to step through code and see variable values in real time.

Troubleshooting common issues

  • Class not found at runtime: ensure file name matches public class name and you compiled with javac.
  • GUI buttons unresponsive: ensure frame.setVisible(true) is called on the Event Dispatch Thread (SwingUtilities.invokeLater).
  • Number parsing errors: trim input and handle locale decimal separators if needed.

Next steps and learning resources

  • Implement an expression evaluator (shunting-yard or recursive descent) to handle full arithmetic expressions with precedence and parentheses.
  • Learn JavaFX for modern GUI development.
  • Explore unit testing with JUnit to verify calculator correctness.
  • Read Java language docs and style guides to improve code quality.

Building a simple Java calculator gives you practical experience with I/O, control flow, data types, and UI basics — skills you’ll reuse in many other projects.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *