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

求教简单计算器问题
下面是我写的一段简单计算器的代码,可是我不知道“=”的相关代码怎么写,来帮帮忙啊

/******************
**Calculator.java**
******************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends WindowAdapter implements ActionListener {
  private JFrame frame;
  private JPanel panel1,panel2;
  private JTextField tf;
  private JButton[] bt;
  private static String number,judge,sign;
  private static Double num,result;
   
  public void work(){
  frame = new JFrame("Normal Calculator");
  panel1 = new JPanel();
  panel2 = new JPanel();
  panel2.setLayout(new GridLayout(4,4));
  tf = new JTextField("0.0",15);
  bt = new JButton[16];
  String[] stringarray = {"0","1","2","3","4","5","6","7","8","9","+","-","*","/",".","="};
  for(int i = 0;i<=15;i++) {
  bt[i] = new JButton(stringarray[i]);
  bt[i].setActionCommand(stringarray[i]);
  bt[i].addActionListener(this);
  }
  number = "";
  judge = "";
  sign = "";
  num = 0.0;
  result = 0.0;
 
  panel1.add(tf);
  int[] orderarray ={7,8,9,10,4,5,6,11,1,2,3,12,0,14,15,13};
  for(int i = 0;i <= 15;i++)
  panel2.add(bt[orderarray[i]]);
  frame.add(panel1,BorderLayout.NORTH);
  frame.add(panel2,BorderLayout.CENTER);
 
  frame.addWindowListener(this);
  frame.setSize(300,250);
  frame.setVisible(true);
  }
   
  public void actionPerformed(ActionEvent e) {
  if("1234567890.".contains(e.getActionCommand())) {
  number += e.getActionCommand();
  tf.setText(number);
  } 
  else {
  if("+-*/".contains(e.getActionCommand())) {
  workOut();
  sign = e.getActionCommand();  
  }
  else workOut();  
  }
  }
   
  public void getNumber() {
  if(number != "") {
  if(judge == "") {
  result = Double.parseDouble(number);
  judge = number;
  number = "";
  }
  else {
  num = Double.parseDouble(number);  
  number = "";
  }
  }
  }
   
  public void workOut() {
  getNumber();
   
  if(sign.equals("+"))
  result += num;  
  if(sign.equals("-"))
  result -= num;  
  if(sign.equals("*"))
  result *= num;
  tf.setText(Double.toString(result));
  if(sign.equals("/")) {
  if(num != 0) {
  result /= num; 
  tf.setText(Double.toString(result));  
  }  
  else tf.setText("error");