用Java语言编写出计算器程序代码,要求:1、上方两个文本框,最上面的文本框为输入文本框,其次是计算结果文本框;
时间: 2024-03-30 20:33:15 浏览: 17
好的,下面是Java语言编写的计算器程序代码,满足您的要求:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField inputField, resultField;
private JButton[] buttons;
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 5, 5));
inputField = new JTextField();
inputField.setHorizontalAlignment(JTextField.RIGHT);
inputField.setEditable(false);
panel.add(inputField);
resultField = new JTextField("0");
resultField.setHorizontalAlignment(JTextField.RIGHT);
resultField.setEditable(false);
panel.add(resultField);
buttons = new JButton[16];
String[] labels = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "C", "0", "=", "/"};
for (int i = 0; i < 16; i++) {
buttons[i] = new JButton(labels[i]);
buttons[i].addActionListener(this);
panel.add(buttons[i]);
}
setContentPane(panel);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("C")) {
inputField.setText("");
resultField.setText("0");
} else if (command.equals("=")) {
try {
String input = inputField.getText();
int result = evaluate(input);
resultField.setText(String.valueOf(result));
} catch (IllegalArgumentException ex) {
resultField.setText("Error");
}
} else {
inputField.setText(inputField.getText() + command);
}
}
private int evaluate(String input) {
String[] tokens = input.split(" ");
if (tokens.length % 2 == 0) {
throw new IllegalArgumentException();
}
int result = Integer.parseInt(tokens[0]);
for (int i = 1; i < tokens.length; i += 2) {
String operator = tokens[i];
int operand = Integer.parseInt(tokens[i + 1]);
if (operator.equals("+")) {
result += operand;
} else if (operator.equals("-")) {
result -= operand;
} else if (operator.equals("*")) {
result *= operand;
} else if (operator.equals("/")) {
result /= operand;
} else {
throw new IllegalArgumentException();
}
}
return result;
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个计算器程序有两个文本框,分别用于输入和输出,还有16个按钮,用于输入数字和运算符。其中,输入和输出文本框都设置为只读,只能通过按钮输入内容。按钮的点击事件会调用actionPerformed方法,通过判断按钮标签来执行相应的操作。对于加、减、乘、除四种运算符,程序使用一个evaluate方法计算结果。