日期:2014-05-20  浏览次数:20644 次

大家来帮小弟看一看这个代码,有什么错误,麻烦了!!!!!
我做的是一个计算器,麻烦大家帮忙看看
package com.Demo;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class CalButtonPane extends JPanel implements ActionListener {
String[] keys = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3","-", "0", "=", ".", "+" };
JButton[] keyButton = new JButton[keys.length];
JTextField t = new JTextField();
JButton Clear;
double resault = 0, num;
int i = 0, j = 0, action;
public CalButtonPane() {
super(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < keys.length; i++) {
keyButton[i] = new JButton(keys[i]);
keyButton[i].addActionListener(this);// 每一个按钮加一个事件监听
this.add(keyButton[i]);
}
Clear = new JButton("Clear");
Clear.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
JButton o = (JButton) e.getSource();
String s = o.getText();
char c = s.charAt(0);
num = Double.parseDouble(t.getText());
if (c == '+') {
if (j == 0)
resault = num;
else if (action == 1)
resault += num;
t.setText(resault + "");
j++;i = 0;action = 1;
} else if (c == '-') {
if (j == 0)
resault = num;
else if (action == 2)
resault -= num;
t.setText(resault + "");
j++;i = 0;action = 2;
} else if (c == '*') {
if (j == 0)
resault = num;
else if (action == 3)
resault *= num;
t.setText(resault + "");
j++;i = 0;action = 3;
} else if (c == '/') {
if (j == 0)
resault = num;
else if (action == 4)
resault /= num;
t.setText(resault + "");
j++;i = 0;action = 4;
} else if (c == '=') {
switch (action) {
case 1:t.setText((resault += num) + "");break;
case 2:t.setText((resault -= num) + "");break;
case 3:t.setText((resault *= num) + "");break;
case 4:t.setText((resault /= num) + "");break;
}
t.setText(resault + "");
i = 0;j = 0;action = 0;
} else if (c == '.') {
if (t.getText().indexOf(".") == -1)
t.setText(t.getText() + c);
} else if (c == 'c') {
i = 0;j = 0;action = 0;
resault = 0;
t.setText("0");
} else {
if (i == 0)
t.setText("");
t.setText(t.getText() + c);
i++;
}

}
}

public class Caculator extends JFrame {
CalButtonPane cp = new CalButtonPane();

public Caculator() {
super("Java计算器");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add(cp.t, "North");
c.add(cp, "Center");
c.add(cp.Clear, "South");
this.setLocation(300, 200);
pack();
this.setResizable(false);
this.setVisible(true);

}

public static void main(String[] args) {
new Caculator();

}

}
总是有错,但是不知道哪不对

------解决方案--------------------
应该添加t.setText("0");要么你之前的JTextField t = new JTextField();t没有赋值,,所以按下按钮时,执行的t.getText()函数出问题,,,后边的判断也会出问题。。。
还有你的else if (c == 'c')出问题,,按钮为Clear,你截取第一个字符,应该为大写C,,所以将'c'改为'C'就可以了。。。