1. 程式人生 > 實用技巧 >Java實現簡單計算器的探索性做法

Java實現簡單計算器的探索性做法

Experiment Content

  Use Java GUI and event handler to realize a simple calculator. This calculator can compute addition, subtraction, multiplication and division of two integer numbers. Besides the above functions, you can realize more functions as possible.

  Requirement: GUI Java application.

1 Requirements Analysis

  In addition to the basic functions of addition, subtraction, multiplication, and division, the calculator program also has a clear key C and a backspace key, as well as some scientific calculation methods, including square root, reverse, and percentage.

  1.1 Basic functions of calculator:

    1.1.1 Addition operation: use the number buttons and the "+" button to perform operations;

    1.1.2 Subtraction operation: use the number buttons and the "-" button to perform operations;

    1.1.3 Multiplication operation: use the number buttons and the "*" button to perform operations;

    1.1.4 Division operation: use the number buttons and the "/" button to perform operations;

  1.2 Backspace key and clear key: Use "Backspace" and "C" buttons to achieve ";

  1.3 Scientific calculation method of calculator:

    1.3.1 Prescribing: Use the number buttons and "Sqrt" button to perform calculations;

    1.3.2 Percentage: Use the number buttons and the "%" button to perform calculations;

    1.3.3 Countdown: use the number buttons and the "1/x" button to perform calculations;

    1.3.4 Negate: use the number buttons and "-/+" buttons to perform operations

2 Design

  2.1 User interface design

  2.1.1 The design of the calculator program: The user interface includes Swing components, but most of the programs use AWT components.

  

  2.1.2 In the AWT component,

  (1) The panel text box is used:

    JPanel panel1, panel2, panel3, panel4;JTextField result;

  2.1.3 In program design, layout management is used: (1) Use GridLayout to set the panel

  

  2.2 Outline design The entire program of the calculator includes: a Calculator class

  2.2.1 Its function is to use graphical users to realize the interface design and calculation functions of the calculator, and some scientific calculation methods include the Calculator() construction method, and other important member methods, and finally instantiate one in the main method The calculator object implements the functions of a calculator.

3 Code(autuor by Ziwei Li)

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class calculator extends JFrame {
   //設定按鈕,包括運算數字和運算子號 
   JButton b0 = new JButton("0");
   JButton b1 = new JButton("1");
   JButton b2 = new JButton("2");
   JButton b3 = new JButton("3");
   JButton b4 = new JButton("4");
   JButton b5 = new JButton("5");
   JButton b6 = new JButton("6");
   JButton b7 = new JButton("7");
   JButton b8 = new JButton("8");
   JButton b9 = new JButton("9");
   JButton jiaButton = new JButton("+");//
   JButton jianButton = new JButton("-");//
   JButton chengButton = new JButton("*");//
   JButton chuButton = new JButton("/");//
   JButton yuButton = new JButton("%");//求餘
   JButton jjButton = new JButton("+/-");//正負
   JButton sqrtButton = new JButton("sqrt");//求根
   JButton dianButton = new JButton(".");//小數點
   JButton dengButton = new JButton("=");//等號
   JButton daoButton = new JButton("1/x");//求1/輸入數
   JButton backButton = new JButton("Backpace");//回退
   JButton cButton = new JButton("C");//清除
   public double op1;
   public double op2;
   public static final int JIA = 0;
   public static final int JIAN = 1;
   public static final int CHENG = 2;
   public static final int CHU = 3;
   public static final int YU = 4;
   public int currentop = 0;
   private boolean opEnd = false;
   //建立面板並進行基本設定
   JPanel panel1 = new JPanel();
   JPanel panel2 = new JPanel();
   JPanel panel3 = new JPanel();
   JPanel panel4 = new JPanel();
   JTextField result = new JTextField(20);
   public calculator() {
      initPanel2();
      initPanel3();
      panel2.setLayout(new GridLayout(5, 4)); //設定總面板邊框
      panel1.setLayout(new BorderLayout(0,0));
      panel1.add(panel3, BorderLayout.NORTH);// 設定位置
      panel1.add(panel2, BorderLayout.CENTER);// 設定位置
      getContentPane().add(panel1);
      addActionListeners();//按鈕監聽器
      setSize(600,400);//窗體大小
      setLocation(500, 300);//窗體位置
      setVisible(true);//窗體顯示
      setDefaultCloseOperation(calculator.EXIT_ON_CLOSE);//窗體關閉
      this.setResizable(false);
      this.setTitle("計算器");
   }


   private void initPanel2() {
      // 把元件新增相應panel上
      panel2.add(b7);
      panel2.add(b8);
      panel2.add(b9);
      panel2.add(chuButton);
      panel2.add(b4);
      panel2.add(b5);
      panel2.add(b6);
      panel2.add(chengButton);
      panel2.add(b1);
      panel2.add(b2);
      panel2.add(b3);
      panel2.add(jianButton);
      panel2.add(b0);
      panel2.add(jjButton);
      panel2.add(dianButton);
      panel2.add(jiaButton);
      panel2.add(daoButton);
      panel2.add(yuButton);
      panel2.add(sqrtButton);
      panel2.add(dengButton);
   }
   private void addActionListeners() {
      ActionHandler c = new ActionHandler();
      //按鈕監聽
      b0.addActionListener(c);
      b1.addActionListener(c);
      b2.addActionListener(c);
      b3.addActionListener(c);
      b4.addActionListener(c);
      b5.addActionListener(c);
      b6.addActionListener(c);
      b7.addActionListener(c);
      b8.addActionListener(c);
      b9.addActionListener(c);
      jiaButton.addActionListener(c);
      dengButton.addActionListener(c);
      chengButton.addActionListener(c);
      chuButton.addActionListener(c);
      jianButton.addActionListener(c);
      jjButton.addActionListener(c);
      dianButton.addActionListener(c);
      sqrtButton.addActionListener(c);
      yuButton.addActionListener(c);
      daoButton.addActionListener(c);
      backButton.addActionListener(c);
      cButton.addActionListener(c);
   }
   private void initPanel3() {
      //輸入和結果顯示
      panel3.setLayout(new GridLayout(2, 1));
      panel3.add(result);
      panel3.add(panel4);
      panel3.setPreferredSize(new Dimension(100,100));
      //清除和回退
      panel4.setLayout(new GridLayout(1, 2));
      panel4.add(backButton);
      panel4.add(cButton);
   }
//運算類
class ActionHandler implements ActionListener {
   public void actionPerformed(ActionEvent e) {
      //輸入數字
      if (e.getSource() == b0) {
         if (opEnd == false) {
            result.setText("");
         }
         result.setText(result.getText() + "0");
      }
      if (e.getSource() == b1) {
         if (opEnd == false) {
            result.setText("");
         }
         result.setText(result.getText() + "1");
         opEnd = true;
      }
      if (e.getSource() == b2) {
         if (opEnd == false) {
            result.setText("");
         }
         result.setText(result.getText() + "2");
         opEnd = true;
      }
      if (e.getSource() == b3) {
         if (opEnd == false) {
            result.setText("");
         }
         result.setText(result.getText() + "3");
         opEnd = true;
      }
      if (e.getSource() == b4) {
         if (opEnd == false) {
            result.setText("");
         }
         result.setText(result.getText() + "4");
         opEnd = true;
      }
      if (e.getSource() == b5) {
         if (opEnd == false) {
            result.setText("");
            }
         result.setText(result.getText() + "5");
         opEnd = true;
      }
      if (e.getSource() == b6) {
         if (opEnd == false) {
            result.setText("");
         }
         result.setText(result.getText() + "6");
         opEnd = true;
      }
      if (e.getSource() == b7) {
         if (opEnd == false) {
            result.setText("");
         }
         result.setText(result.getText() + "7");
         opEnd = true;
      }
      if (e.getSource() == b8) {
         if (opEnd == false) {
            result.setText("");
         }
         result.setText(result.getText() + "8");
         opEnd = true;
      }
      if (e.getSource() == b9) {
         if (opEnd == false) {
            result.setText("");
         }
         result.setText(result.getText() + "9");
         opEnd = true;
      }
      try {
         if (e.getSource() == jiaButton) {//點選+按鈕,下同
            op1 = Double.parseDouble(result.getText());
            //說明運算元已經輸入完畢
            opEnd = false;
            currentop = JIA;
         }
         if (e.getSource() == chengButton) {//
            op1 = Double.parseDouble(result.getText());
            //說明運算元已經輸入完畢
            opEnd = false;
            currentop = CHENG;
         }
         if (e.getSource() == chuButton) {//
            op1 = Double.parseDouble(result.getText());
            //說明運算元已經輸入完畢
            opEnd = false;
            currentop = CHU;
         }
         if (e.getSource() == jianButton) {//
            op1 = Double.parseDouble(result.getText());
            //說明運算元已經輸入完畢
            opEnd = false;
            currentop = JIAN;
         }
         if (e.getSource() == yuButton) {//
            op1 = Double.parseDouble(result.getText());
            //說明運算元已經輸入完畢
            opEnd = false;
            currentop = YU;
         }
         if (e.getSource() == jjButton) {//正負
            String tmp = result.getText();
            if (tmp.equals("") || tmp.equals("0")) {
               return;
            }
            if (tmp.charAt(0) == '-') {
               tmp = tmp.substring(1);
            } else {
               tmp = '-' + tmp;
            }
            result.setText(tmp);
         }
         if (e.getSource() == dianButton) {//小數點
            String tmp = result.getText();
            if (tmp.equals("")) {
               return;
            }
            if (tmp.indexOf(".") != -1) {
               return;
            }
            tmp = tmp + ".";
            result.setText(tmp);
         }
         if(e.getSource() == daoButton) {//1/x
            String tmp = result.getText();
            if (tmp.equals(" ")) {
               return;
            }
            double d; // 先定義d
            d = Double.parseDouble(tmp);
            if(d==0) {
               result.setText("被除數不能為零");
               return;
            }
            op2 = 1/d;
            result.setText(op2 + "");
         }
         if (e.getSource() == sqrtButton) {//求根
            String tmp = result.getText();
            if (tmp.equals(" ")) {
               return;
            }
            double d;
            d = Double.parseDouble(tmp);
            if (d < 0) {
               result.setText("不能對負數求平方根");
               return;
            }
            op2 = Math.sqrt(d);
            result.setText(op2 + "");
         }
         if (e.getSource() == backButton) {//回退
            String s = result.getText();
            result.setText("");
            for (int i = 0; i < s.length() - 1; i++) {
               char a = s.charAt(i);
               result.setText(result.getText() + a);
            }
         }
         if (e.getSource() == cButton) {//清除
            result.setText("0");
            opEnd = false;
         }
         if (e.getSource() == dengButton) { //點選“=”按鈕
            op2 = Double.parseDouble(result.getText());
            switch (currentop) {
            case JIA:
               result.setText(op1 + op2 + "");
               break;
            case JIAN:
               result.setText(op1 - op2 + "");
               break;
            case CHENG:
               result.setText(op1 * op2 + "");
               break;
            case CHU:
               if (op2 == 0) {
                  result.setText("0不能為除數");
                  break;
               }
               result.setText(op1 / op2 + "");
               break;
            case YU:
               if (op2 == 0) {
                  result.setText("0不能為除數");
                  break;
               }
               result.setText(op1 % op2 + "");
               break;
            }
            opEnd = false;
         }
      } catch (Exception e1) {
         result.setText("輸入有誤,請重新輸入");
         opEnd = false;
      }
      }
   }
   public static void main(String[] args) {
      new calculator();// 生成類例項
   }
 

4 Test

4.1 Implement addition: 1+2+3=6

Return:5

Error