Java

java实现计算器模板及源码

小云
103
2023-08-10 13:03:00
栏目: 编程语言

以下是一个简单的 Java 计算器的实现:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator {
private JFrame frame;
private JTextField inputField;
private JButton[] numberButtons;
private JButton[] operatorButtons;
private JButton calculateButton;
private JButton clearButton;
public Calculator() {
frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
frame.setLayout(new GridLayout(5, 4));
inputField = new JTextField();
frame.add(inputField);
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
frame.add(numberButtons[i]);
}
operatorButtons = new JButton[4];
operatorButtons[0] = new JButton("+");
operatorButtons[1] = new JButton("-");
operatorButtons[2] = new JButton("*");
operatorButtons[3] = new JButton("/");
for (int i = 0; i < 4; i++) {
frame.add(operatorButtons[i]);
}
calculateButton = new JButton("=");
frame.add(calculateButton);
clearButton = new JButton("C");
frame.add(clearButton);
frame.setVisible(true);
// 设置按钮的监听器
for (int i = 0; i < 10; i++) {
int finalI = i;
numberButtons[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
inputField.setText(inputField.getText() + finalI);
}
});
}
for (int i = 0; i < 4; i++) {
int finalI = i;
operatorButtons[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
inputField.setText(inputField.getText() + operatorButtons[finalI].getText());
}
});
}
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String expression = inputField.getText();
double result = 0;
// TODO: 实现计算逻辑
// 这里只是一个示例,只实现了加法运算
if (expression.contains("+")) {
String[] numbers = expression.split("\\+");
double num1 = Double.parseDouble(numbers[0]);
double num2 = Double.parseDouble(numbers[1]);
result = num1 + num2;
}
inputField.setText(String.valueOf(result));
}
});
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
inputField.setText("");
}
});
}
public static void main(String[] args) {
new Calculator();
}
}

这个计算器使用了 Java 的 Swing 库来创建图形界面。它包含一个文本框用于显示输入和计算结果,数字按钮用于输入数字,操作按钮用于输入运算符,计算按钮用于执行计算,清除按钮用于清除输入。在计算按钮的监听器中,可以自己实现计算逻辑。上面的示例只实现了简单的加法运算,你可以根据需要自己扩展实现其他运算。

0
看了该问题的人还看了