溫馨提示×

java實現(xiàn)計算器模板及源碼

小云
103
2023-08-10 13:03:00
欄目: 編程語言

以下是一個簡單的 Java 計算器的實現(xiàn):

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);
// 設(shè)置按鈕的監(jiān)聽器
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: 實現(xiàn)計算邏輯
// 這里只是一個示例,只實現(xiàn)了加法運算
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 庫來創(chuàng)建圖形界面。它包含一個文本框用于顯示輸入和計算結(jié)果,數(shù)字按鈕用于輸入數(shù)字,操作按鈕用于輸入運算符,計算按鈕用于執(zhí)行計算,清除按鈕用于清除輸入。在計算按鈕的監(jiān)聽器中,可以自己實現(xiàn)計算邏輯。上面的示例只實現(xiàn)了簡單的加法運算,你可以根據(jù)需要自己擴展實現(xiàn)其他運算。

0