I'm pretty sure I've looked at most of the questions related to this issue, but they all use multiple text fields, one listener per button, or something like that. I'm trying to get multiple double inputs from one text field, where a first variable is set to the initial text and a second variable is set to the second text. So if someone enters 1 + 4, the first variable is set to 1, the + clears the text field, and the second variable is set to 4. This is a first write up so there might be a lot of unnecessary things.
EDIT: Might've been unclear here, what I want to happen is the user enters (for 1 + 4), click button 1 setting the text field to 1 and setting the first variable to 1, then click the + button which clears the text field, then click the 4 button setting the text field to 4 and setting the second variable to 4, then click the equals button, and the result is based off the operator clicked. It's not entered all as one string.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class GUICalculator extends JFrame implements ActionListener {
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
private JTextField displayField;
private static final String[] NUMBERS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-", "*", "/", "C", "=", "."};
private static final Set<String> OPERATORS = new HashSet<>(Arrays.asList("+", "-", "*", "/", "C", "="));
private double n1, n2, result;
public GUICalculator() {
super("Calculator");
setLayout(new BorderLayout());
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
displayField = new JTextField();
displayField.setEditable(false);
add(displayField, BorderLayout.NORTH);
add(buttonPanel);
for (String number : NUMBERS) {
JButton buttons = new JButton(number);
buttons.addActionListener(this);
buttonPanel.add(buttons);
}
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
for (String number : NUMBERS) {
if (command.equals(number) && !OPERATORS.contains(command)) {
displayField.setText(displayField.getText() + command);
n1 = Double.parseDouble(displayField.getText());
}
//n2 = Double.parseDouble(displayField.getText());
switch (command) {
case "+":
result = n1 + n2;
displayField.setText("");
case "-":
result = n1 - n2;
displayField.setText("");
case "*":
result = n1 * n2;
displayField.setText("");
case "/":
try {
if (n2 == 0)
throw new DivisionByZeroException();
result = n1 / n2;
} catch (DivisionByZeroException f) {
f.getMessage();
displayField.setText("");
break;
}
case "=":
displayField.setText(Double.toString(result));
break;
case "C":
displayField.setText("");
}
}
}
public static void main(String[] args) {
GUICalculator gc = new GUICalculator();
gc.setVisible(true);
}
}
The commented line is what I want to go in, but I have no idea where to put it.