java计算器项目
题目:java计算器项目
一、 题目简介: 一个能进行加减乘除四则运算的小程序
Github链接:https://github.com/lizhenbin/test/tree/master/Calculator
代码如下:
import java.awt.; import java.awt.event.; import javax.swing.*;
public class JCalculator extends JFrame implements ActionListener {
private static final long serialVersionUID = -169068472193786457L;
//关闭计算器
private class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
int i;
//添加数字按钮
private final String[] str = { "7", "8", "9", "/", "4", "5", "6", "*", "1",
"2", "3", "-", ".", "0", "=", "+" };
JButton[] buttons = new JButton[str.length];
JButton reset = new JButton("CE");
// 编译
JTextField display = new JTextField("0");
public JCalculator() {
super("Calculator");
JPanel panel1 = new JPanel(new GridLayout(4, 4));
for (i = 0; i < str.length; i++) {
buttons[i] = new JButton(str[i]);
panel1.add(buttons[i]);
}
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add("Center", display);
panel2.add("East", reset);
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", panel2);
getContentPane().add("Center", panel1);
// 添加监听器
for (i = 0; i < str.length; i++)
buttons[i].addActionListener(this);
reset.addActionListener(this);
// 添加一个显示按钮
display.addActionListener(this);
// 关闭按钮“X”
addWindowListener(new WindowCloser());
// 改变窗口大小
setSize(800, 800);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e) {
Object target = e.getSource();
String label = e.getActionCommand();
if (target == reset)
handleReset();
else if ("0123456789.".indexOf(label) > 0)
handleNumber(label);
else
handleOperator(label);
}
boolean isFirstDigit = true;
public void handleNumber(String key) {
if (isFirstDigit)
display.setText(key);
else if ((key.equals(".")) && (display.getText().indexOf(".") < 0))
display.setText(display.getText() + ".");
else if (!key.equals("."))
display.setText(display.getText() + key);
isFirstDigit = false;
}
public void handleReset() {
display.setText("0");
isFirstDigit = true;
operator = "=";
}
double number = 0.0;
String operator = "=";
public void handleOperator(String key) {
if (operator.equals("+"))
number += Double.valueOf(display.getText());
else if (operator.equals("-"))
number -= Double.valueOf(display.getText());
else if (operator.equals("*"))
number *= Double.valueOf(display.getText());
else if (operator.equals("/"))
number /= Double.valueOf(display.getText());
else if (operator.equals("="))
number = Double.valueOf(display.getText());
display.setText(String.valueOf(number));
operator = key;
isFirstDigit = true;
}
public static void main(String[] args) {
new JCalculator();
}
}
三、 结对分工情况 代码编写:李振斌 测试,校对:张义军
四、 所设计的模块测试用例、测试结果截图
五、问题及解决方案、心得体会 本次实验设计了一个简单的java加速器程序,进一步学习了Github的使用方法, 进一步学习了Junit4的相关知识,增进了对Java的理解,对合作学习有了更清晰的认识。 两人协作编程更容易找到错误,对编程很有帮助。