利用java做一个计算器窗口,其功能实现加减乘除以及% sqrt log10
时间: 2024-02-23 11:59:37 浏览: 159
好的,我可以帮你实现这个功能。你需要创建一个 Java 项目,并且在项目中创建一个 Calculator 类。下面是一个实现加减乘除、%、sqrt、log10 功能的示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField numberField;
private JButton addButton, subtractButton, multiplyButton, divideButton, modButton, sqrtButton, log10Button;
private double result = 0;
private String operator = "";
public Calculator() {
frame = new JFrame("Calculator");
frame.setLayout(new FlowLayout());
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
numberField = new JTextField(10);
frame.add(numberField);
addButton = new JButton("+");
addButton.addActionListener(this);
frame.add(addButton);
subtractButton = new JButton("-");
subtractButton.addActionListener(this);
frame.add(subtractButton);
multiplyButton = new JButton("*");
multiplyButton.addActionListener(this);
frame.add(multiplyButton);
divideButton = new JButton("/");
divideButton.addActionListener(this);
frame.add(divideButton);
modButton = new JButton("%");
modButton.addActionListener(this);
frame.add(modButton);
sqrtButton = new JButton("sqrt");
sqrtButton.addActionListener(this);
frame.add(sqrtButton);
log10Button = new JButton("log10");
log10Button.addActionListener(this);
frame.add(log10Button);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
double number = Double.parseDouble(numberField.getText());
if (e.getSource() == addButton) {
result += number;
operator = "+";
} else if (e.getSource() == subtractButton) {
result -= number;
operator = "-";
} else if (e.getSource() == multiplyButton) {
result *= number;
operator = "*";
} else if (e.getSource() == divideButton) {
result /= number;
operator = "/";
} else if (e.getSource() == modButton) {
result %= number;
operator = "%";
} else if (e.getSource() == sqrtButton) {
result = Math.sqrt(number);
operator = "sqrt";
} else if (e.getSource() == log10Button) {
result = Math.log10(number);
operator = "log10";
}
numberField.setText("");
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个示例代码实现了一个简单的计算器窗口,包括一个文本框用于输入数字,以及加减乘除、%、sqrt、log10 等按钮。当用户点击按钮时,程序会根据按钮的功能进行相应的计算,并在文本框中显示结果。你可以根据自己的需求进行修改和扩展。
阅读全文