java中awt写一个混合计算的计算器
时间: 2024-03-07 21:50:12 浏览: 50
以下是一个简单的混合计算的计算器的示例代码:
```java
import java.awt.*;
import java.awt.event.*;
public class Calculator extends Frame implements ActionListener {
TextField tf;
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, bAdd, bSub, bMul, bDiv, bEq, bClr;
double num1, num2, result;
char op;
public Calculator() {
tf = new TextField();
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
b5 = new Button("5");
b6 = new Button("6");
b7 = new Button("7");
b8 = new Button("8");
b9 = new Button("9");
b0 = new Button("0");
bAdd = new Button("+");
bSub = new Button("-");
bMul = new Button("*");
bDiv = new Button("/");
bEq = new Button("=");
bClr = new Button("C");
setLayout(new FlowLayout());
add(tf);
add(b1);
add(b2);
add(b3);
add(bAdd);
add(b4);
add(b5);
add(b6);
add(bSub);
add(b7);
add(b8);
add(b9);
add(bMul);
add(b0);
add(bClr);
add(bEq);
add(bDiv);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
bAdd.addActionListener(this);
bSub.addActionListener(this);
bMul.addActionListener(this);
bDiv.addActionListener(this);
bEq.addActionListener(this);
bClr.addActionListener(this);
setSize(200, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String s = ae.getActionCommand();
if (s.equals("C")) {
tf.setText("");
num1 = 0;
num2 = 0;
result = 0;
}
else if (s.equals("+")) {
num1 = Double.parseDouble(tf.getText());
op = '+';
tf.setText("");
}
else if (s.equals("-")) {
num1 = Double.parseDouble(tf.getText());
op = '-';
tf.setText("");
}
else if (s.equals("*")) {
num1 = Double.parseDouble(tf.getText());
op = '*';
tf.setText("");
}
else if (s.equals("/")) {
num1 = Double.parseDouble(tf.getText());
op = '/';
tf.setText("");
}
else if (s.equals("=")) {
num2 = Double.parseDouble(tf.getText());
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
tf.setText("" + result);
}
else {
String temp = tf.getText();
temp += s;
tf.setText(temp);
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
运行该程序,可以看到一个简单的混合计算的计算器界面,支持加、减、乘、除四种运算以及清除、等于、小数点等操作。
阅读全文