有没有大佬给看下这个代码哪里有问题。不管运行什么,都显示“ERROR”
package MYM;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MYM {
// Declare frame, text field and buttons
private JFrame frame;
private JTextField textField;
private String currentInput = "";
// Constructor to setup GUI components
public MYM() {
// Create frame
frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.setLayout(new BorderLayout());
// Create text field for input and result display
textField = new JTextField();
textField.setFont(new Font("Arial", Font.PLAIN, 24));
textField.setEditable(false);
frame.add(textField, BorderLayout.NORTH);
// Create panel for buttons
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4)); // Increased rows to 5 to add a row for the delete button
// Define button labels
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"C", "←" // "←" is the delete button
};
// Add buttons to the panel
for (String label : buttons) {
JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.PLAIN, 24));
button.addActionListener(new ButtonClickListener());
panel.add(button);
}
// Add panel to the frame
frame.add(panel, BorderLayout.CENTER);
// Make frame visible
frame.setVisible(true);
}
// ActionListener for button clicks
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
// Evaluate the expression and show result
try {
currentInput = evaluateExpression(currentInput);
textField.setText(currentInput);
} catch (Exception ex) {
textField.setText("Error");
}
} else if (command.equals("C")) {
// Clear the input
currentInput = "";
textField.setText(currentInput);
} else if (command.equals("←")) {
// Delete the last character
if (currentInput.length() > 0) {
currentInput = currentInput.substring(0, currentInput.length() - 1);
textField.setText(currentInput);
}
} else {
// Append the pressed button to the current input
currentInput += command;
textField.setText(currentInput);
}
}
}
// Function to evaluate simple arithmetic expressions
private String evaluateExpression(String expression) {
try {
// Evaluate the expression using Java's built-in script engine
javax.script.ScriptEngineManager mgr = new javax.script.ScriptEngineManager();
javax.script.ScriptEngine engine = mgr.getEngineByName("JavaScript");
Object result = engine.eval(expression);
return result.toString();
} catch (Exception e) {
return "Error";
}
}
public static void main(String[] args) {
// Create an instance of the Calculator
new MYM();
}
}