4
回答
计算器还可以怎么减少代码行
终于搞明白,存储TCO原来是这样算的>>>   
import java.awt.*;
import java.awt.event.*;

class CalculatorFrame extends Frame {
 public TextField text;
 public Panel pCenter;//, pSouth;
 public Button clear;//, e;
 public GridLayout grid;
 public double result;
 public String lastCommand;
 public boolean start;
 CalculatorFrame() {
  setLayout(new BorderLayout());
     result = 0;
        lastCommand = "=";
        start = true;
  text = new TextField();
  pCenter = new Panel();
  clear = new Button("clear");
  grid = new GridLayout(4, 4, 5, 5);
  pCenter.setLayout(grid);
  ActionListener insert = new InsertAction();
        ActionListener command = new CommandAction();
  ActionListener clear_1 = new ClearAction();

  addButton("7", insert);
        addButton("8", insert);
        addButton("9", insert);
  addButton("+", command);
  addButton("4", insert);
        addButton("5", insert);
        addButton("6", insert);
  addButton("-", command);
  addButton("1", insert);
        addButton("2", insert);
        addButton("3", insert);
  addButton("*", command);
  addButton(".", insert);
  addButton("0", insert);
  addButton("=", command);
        addButton("/", command);
  add(text, BorderLayout.NORTH);
  add(pCenter, BorderLayout.CENTER);
  add(clear, BorderLayout.SOUTH);
  clear.addActionListener(clear_1);
  setVisible(true);
  setSize(400, 400);
 }

 public void addButton(String label, ActionListener listener) {
        Button button = new Button(label);
        button.addActionListener(listener);
        pCenter.add(button);
    }

 class InsertAction implements ActionListener {//点击按钮监听器类
  public void actionPerformed(ActionEvent event) {
   String input = event.getActionCommand();
   if (start) {
    text.setText("");
    start = false;
   }
   text.setText(text.getText() + input);
  }
 }

 class CommandAction implements ActionListener { //点击按钮监听器类
  public void actionPerformed(ActionEvent evt) {
   String command = evt.getActionCommand();
   if (start) {
    lastCommand = command;
   }else {
    calculate(Double.parseDouble(text.getText()));
    lastCommand = command;
    start = true;
   }
  }
 }

 class ClearAction implements ActionListener {
  public void actionPerformed(ActionEvent e) {
   text.setText(null);
  }
 }

 public void calculate(double x) {  //计算
        if (lastCommand.equals("+")) {
            result += x;
        } else if (lastCommand.equals("-")) {
            result -= x;
        } else if (lastCommand.equals("*")) {
            result *= x;
        } else if (lastCommand.equals("/")) {
            result /= x;
        } else if (lastCommand.equals("=")) {
            result = x;
        }
        text.setText("" + result);
    }
}

public class Calculator {
    public static void main(String[] args) {
        CalculatorFrame frame = new CalculatorFrame(); 
    }
}
<无标签>
举报
Mattew
发帖于5年前 4回/219阅
顶部