java实现加减乘除_用Java编写实现加减乘除,界面如下
时间: 2023-07-18 09:24:25 浏览: 111
我可以给你提供一个简单的Java实现,包括一个基本的界面和加减乘除的计算功能。你可以根据自己的需求修改和扩展它。
代码如下:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField textField;
private JButton addButton, subtractButton, multiplyButton, divideButton, clearButton, equalsButton;
private double firstNumber, secondNumber, result;
private String operator;
public Calculator() {
// 创建界面
frame = new JFrame("简单计算器");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
// 创建文本框
textField = new JTextField();
textField.setEditable(false);
textField.setHorizontalAlignment(SwingConstants.RIGHT);
// 创建按钮
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
clearButton = new JButton("C");
equalsButton = new JButton("=");
// 添加按钮监听器
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
clearButton.addActionListener(this);
equalsButton.addActionListener(this);
// 创建面板
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
panel.add(addButton);
panel.add(subtractButton);
panel.add(multiplyButton);
panel.add(divideButton);
panel.add(new JButton("7"));
panel.add(new JButton("8"));
panel.add(new JButton("9"));
panel.add(new JButton("4"));
panel.add(new JButton("5"));
panel.add(new JButton("6"));
panel.add(new JButton("1"));
panel.add(new JButton("2"));
panel.add(new JButton("3"));
panel.add(clearButton);
panel.add(new JButton("0"));
panel.add(equalsButton);
// 添加组件到窗口
frame.getContentPane().add(textField, BorderLayout.NORTH);
frame.getContentPane().add(panel, BorderLayout.CENTER);
// 显示窗口
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("C")) {
// 清空文本框和操作数
textField.setText("");
firstNumber = 0;
secondNumber = 0;
result = 0;
operator = "";
} else if (command.equals("+") || command.equals("-") || command.equals("*") || command.equals("/")) {
// 记录第一个操作数和操作符
firstNumber = Double.parseDouble(textField.getText());
operator = command;
textField.setText("");
} else if (command.equals("=")) {
// 计算结果
secondNumber = Double.parseDouble(textField.getText());
if (operator.equals("+")) {
result = firstNumber + secondNumber;
} else if (operator.equals("-")) {
result = firstNumber - secondNumber;
} else if (operator.equals("*")) {
result = firstNumber * secondNumber;
} else if (operator.equals("/")) {
result = firstNumber / secondNumber;
}
textField.setText("" + result);
} else {
// 添加数字到文本框
textField.setText(textField.getText() + command);
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
```
这个程序使用了Java Swing库来创建界面和组件,实现了加减乘除的计算功能。你可以根据自己的需求修改和扩展它。
阅读全文