急求Java计算器代码注释!!!!!

2025-03-01 17:02:46
推荐回答(2个)
回答1:

其实你这种学习编程的方法我是极度不推荐的,正确的方法应该从基础开始,你这个程序是用图形用户界面来写的,入门的话最好还是控制台程序,这样你可以了解整个程序的流程和语法,如果你没有C语言的基础,请找一本讲解C语言的书学习,然后学习好了你再来看JAVA感觉就很简单了。(绝对原创,请求给分)

import java.awt.*;
import java.awt.event.*; //导入包,因为后面要用到里面的东西

public class jisuanqi extends WindowAdapter {
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel(); //构造3个panel对象,这个是个容器,里面可以添加别的组件
TextField txt; // TextField 组件,相当于一个文本区域
private Button[] b = new Button[17]; //看名字就知道是按钮了吧
private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
"3", "*", "清空", "0", "=", "/", "关闭" };
static int a;
static String s, str;
//入口函数,相当于C里面的MAIN函数
public static void main(String args[]) {
(new jisuanqi()).frame(); //调用函数,java里叫方法
}
//将窗口实例化,frame是一个窗口,awt包里的。算法方面自己看看就能明白
public void frame() {
Frame fm = new Frame("简单计算器");
for (int i = 0; i <= 16; i++) {
b[i] = new Button(ss[i]);
}
for (int i = 0; i <= 15; i++) {
p2.add(b[i]);
}

fm.setBounds(300,200,200,200);

b[16].setBackground(Color.yellow);
txt = new TextField(15);
txt.setEditable(false);
for (int i = 0; i <= 16; i++) {
b[i].addActionListener(new buttonlistener());
}
b[16].addActionListener(new close());
fm.addWindowListener(this);
fm.setBackground(Color.red);
p1.setLayout(new BorderLayout());
p1.add(txt, "Center");
p2.setLayout(new GridLayout(4, 4));
p3.setLayout(new BorderLayout());
p3.add(b[16]);
fm.add(p1, "North");
fm.add(p2, "Center");
fm.add(p3, "South");
fm.pack();
fm.setVisible(true);
}
//关闭窗口的方法
public void windowClosing(WindowEvent e) {
System.exit(0);
}
//用这种方法在一个类里面定义另一个类是不好的,应该单独用以个文件承载,这个类是实现了ActionListener接口,用于监听按钮事件。正规的写法应该是在主类里面实现这个接口,然后写一个方法来调用。
class buttonlistener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
if (btn.getLabel() == "=") {
jisuan();
str = String.valueOf(a);
txt.setText(str);
s = "";
} else if (btn.getLabel() == "+") {
jisuan();
txt.setText("");
s = "+";
} else if (btn.getLabel() == "-") {
jisuan();
txt.setText("");
s = "-";
} else if (btn.getLabel() == "/") {
jisuan();
txt.setText("");
s = "/";

} else if (btn.getLabel() == "*") {
jisuan();
txt.setText("");
s = "*";
} else {
txt.setText(txt.getText() + btn.getLabel());

if (btn.getLabel() == "清空")
txt.setText("");
}
}

public void jisuan() {
if (s == "+")
a += Integer.parseInt(txt.getText());
else if (s == "-")
a -= Integer.parseInt(txt.getText());
else if (s == "*")
a *= Integer.parseInt(txt.getText());
else if (s == "/")
a /= Integer.parseInt(txt.getText());
else
a = Integer.parseInt(txt.getText());
}
}
}
//关闭按钮事件
class close implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}

回答2:

http://hi.baidu.com/mm%5Fzone/blog/item/be289f18095aa3b74aedbc31.html
看一下我空间里的代码吧,注释也不多,不过应该对你有帮助