code a calculator with Java
- User
code a calculator with Java
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
code a calculator with Java
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course! Here are two ways to code a calculator in Java.
This version runs in your terminal or command prompt. It asks you for two numbers and an operator, then prints the result.
Calculator.javaimport java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double num1, num2, result;
char operator;
System.out.println("--- Java Command-Line Calculator ---");
while (true) {
System.out.print("Enter first number: ");
// Check if the input is a valid number
if (!reader.hasNextDouble()) {
System.out.println("Invalid input. Please enter a number.");
reader.next(); // Consume the invalid input
continue;
}
num1 = reader.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
operator = reader.next().charAt(0);
System.out.print("Enter second number: ");
if (!reader.hasNextDouble()) {
System.out.println("Invalid input. Please enter a number.");
reader.next(); // Consume the invalid input
continue;
}
num2 = reader.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
// Check for division by zero
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error! Cannot divide by zero.");
continue; // Skip the rest of the loop and start over
}
break;
default:
System.out.printf("Error! Operator '%c' is not correct%n", operator);
continue; // Skip the rest of the loop and start over
}
// Print the result
System.out.println("---------------------------------");
System.out.printf("%.2f %c %.2f = %.2f%n", num1, operator, num2, result);
System.out.println("---------------------------------");
System.out.print("Do you want to perform another calculation? (yes/no): ");
String continueChoice = reader.next();
if (!continueChoice.equalsIgnoreCase("yes")) {
break; // Exit the while loop
}
}
System.out.println("Calculator is closing. Goodbye!");
reader.close();
}
}
Scanner: We use java.util.Scanner to get user input from the command line.num1, num2 for the numbers (using double to allow decimals), and operator for the math symbol (char).while(true) loop: This makes the calculator run continuously until the user decides to exit.reader.hasNextDouble() to check if the user entered a valid number. If not, it prints an error and restarts the loop.switch Statement: This is the core of the calculator. It checks which operator the user entered and performs the correct calculation./ case, it checks if num2 is zero. If it is, it prints an error instead of crashing the program.% or ^), the default case handles it with an error message.break statement exits the while loop.reader.close() is called after the loop to release system resources.Calculator.java.javac Calculator.javajava CalculatorThis creates a window with buttons and a display, making it feel like a standard desktop application.
GuiCalculator.javaimport javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuiCalculator extends JFrame implements ActionListener {
// The display text field
private JTextField display;
// Variables to store the operator and the first number
private String operator;
private double num1;
private boolean isOperatorClicked = false;
public GuiCalculator() {
// --- Frame Setup ---
setTitle("GUI Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// --- Display Field ---
display = new JTextField();
display.setEditable(false);
display.setFont(new Font("Arial", Font.PLAIN, 32));
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
// --- Button Panel ---
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 10, 10)); // 4x4 grid with spacing
// Button labels
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};
// Create and add buttons to the panel
for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.BOLD, 24));
button.addActionListener(this); // Register the listener
buttonPanel.add(button);
}
add(buttonPanel, BorderLayout.CENTER);
// Make the frame visible
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand(); // Get the text from the button
// If the command is a number
if ("0123456789".contains(command)) {
if (isOperatorClicked) {
display.setText(command);
isOperatorClicked = false;
} else {
display.setText(display.getText() + command);
}
}
// If the command is an operator
else if ("+-*/".contains(command)) {
num1 = Double.parseDouble(display.getText());
operator = command;
isOperatorClicked = true;
}
// If the command is "="
else if (command.equals("=")) {
double num2 = Double.parseDouble(display.getText());
double result = 0;
switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
display.setText("Error");
return;
}
break;
}
// Display result, removing ".0" for whole numbers
if (result == (int)result) {
display.setText(String.valueOf((int)result));
} else {
display.setText(String.valueOf(result));
}
isOperatorClicked = true; // Ready for a new calculation
}
// If the command is "C" (Clear)
else if (command.equals("C")) {
display.setText("");
num1 = 0;
operator = null;
isOperatorClicked = false;
}
}
public static void main(String[] args) {
// Run the GUI in the Event Dispatch Thread for thread safety
SwingUtilities.invokeLater(() -> new GuiCalculator());
}
}
javax.swing.* for GUI components and java.awt.* for layout and events.extends JFrame (to act as a window) and implements ActionListener (to listen for button clicks).GuiCalculator():
JFrame).JTextField to act as the calculator's display screen.JPanel with a GridLayout to hold the buttons in a neat grid."7", "8", etc.), creates a JButton for each, and adds them to the panel.button.addActionListener(this); tells each button that our GuiCalculator class will handle its click events.actionPerformed(ActionEvent e) method: This method is automatically called whenever any button is clicked.
e.getActionCommand() gets the label of the button that was pressed (e.g., "5", "+", "=").isOperatorClicked flag helps start a new number after an operator has been pressed.num1, the operator is stored, and the display is cleared for the next number.num1 and operator, and shows the result.main method: This is the entry point. SwingUtilities.invokeLater is the standard, thread-safe way to create and show a Swing GUI.GuiCalculator.java.javac GuiCalculator.javajava GuiCalculator