程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java編寫的計算器程序及源代碼

Java編寫的計算器程序及源代碼

編輯:關於JAVA

//frame版程序源代碼如下,疏漏之處,望批評指正。
//數字分組沒有編寫,科學型計算器沒有編寫,其他已經完善。
import java.awt.*;
import java.lang.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class Calculator
  implements ActionListener { //導入動作監聽接口
 //設計面板中的單位
 JFrame frame;
 JTextField textAnswer;
 JPanel panel, panel1, panel2, panel3;
 JMenuBar mainMenu;
 JTextField textMemory;
 JLabel labelMemSpace; //labelMemSpace單純做擺設,控制面板的形狀
 JButton buttonBk, buttonCe, buttonC;
 JButton button[];
 JButton buttonMC, buttonMR, buttonMS, buttonMAdd;
 JButton buttonDot, buttonAddAndSub, buttonAdd, buttonSub, buttonMul,
   buttonDiv, buttonMod;
 JButton buttonSqrt, buttonDao, buttonEqual;
 JMenu editMenu, viewMenu, helpMenu;
 JMenuItem copyItem, pasteItem, tItem, sItem, numberGroup, topHelp, aboutCal;
 DecimalFormat df; //設置數據輸出精度
 boolean clickable; //控制當前能否按鍵
 double memoryd; //使用內存中存儲的數字
 int memoryi;
 double vard, answerd; //用來保存double型數據的中間值(vard)和最後結果(answerd)
 short key = -1, prekey = -1; //key用來保存當前進行何種運算,prekey用來保存前次進行何種運算
 String copy; //做復制用
 JTextArea help; //幫助
 JScrollPane scrollHelp;
 //構造函數
 public Calculator() {
  clickable = true;
  answerd = 0;
  frame = new JFrame("計算器");
  df = new DecimalFormat("0.##############"); //設置數據輸出精度(對於double型值)
  textAnswer = new JTextField(15);
  textAnswer.setText("");
  textAnswer.setEditable(false);
  textAnswer.setBackground(new Color(255, 255, 255));
  panel = new JPanel();
  frame.getContentPane().add(panel);
  panel1 = new JPanel();
  panel2 = new JPanel();
  panel.setLayout(new BorderLayout());
  //設計整個面板
  mainMenu = new JMenuBar();
  editMenu = new JMenu("編輯(E)");
  viewMenu = new JMenu("查看(V)");
  helpMenu = new JMenu("幫助(H)");
  copyItem = new JMenuItem("  復制(C) Ctrl+C");
  copyItem.addActionListener(this);
  pasteItem = new JMenuItem("  粘貼(V) Ctrl+V");
  pasteItem.addActionListener(this);
  editMenu.add(copyItem);
  editMenu.add(pasteItem);
  tItem = new JMenuItem("●標准型(T)");
  tItem.addActionListener(this);
  sItem = new JMenuItem("  科學型(S)");
  sItem.addActionListener(this);
  numberGroup = new JMenuItem("  數字分組(I)");
  numberGroup.addActionListener(this);
  viewMenu.add(tItem);
  viewMenu.add(sItem);
  viewMenu.add(numberGroup);
  topHelp = new JMenuItem("  幫助主題(H)");
  topHelp.addActionListener(this);
  help = new JTextArea(5, 20);
  scrollHelp = new JScrollPane(help);
  help.setEditable(false);
  help.append("執行簡單計算\n");
  help.append("1. 鍵入計算的第一個數字。\n");
  help.append("2. 單擊“+”執行加、“-”執行減、“*”執行乘或“/”執行除。\n");
  help.append("3. 鍵入計算的下一個數字。\n");
  help.append("4. 輸入所有剩余的運算符和數字。\n");
  help.append("5. 單擊“=”。\n");
  aboutCal = new JMenuItem("  關於計算器(A)");
  aboutCal.addActionListener(this);
  helpMenu.add(topHelp);
  helpMenu.add(aboutCal);
  mainMenu.add(editMenu);
  mainMenu.add(viewMenu);
  mainMenu.add(helpMenu);
  panel.add(mainMenu, BorderLayout.NORTH);
  panel.add(textAnswer, BorderLayout.CENTER);
  panel.add(panel1, BorderLayout.SOUTH);
  panel1.setLayout(new BorderLayout());
  textMemory = new JTextField(3);
  textMemory.setEditable(false);
  textMemory.setBackground(new Color(217, 217, 217));
  labelMemSpace = new JLabel("          ");
  buttonBk = new JButton("Backspace");
  buttonBk.setForeground(new Color(255, 0, 0));
  buttonCe = new JButton("CE");
  buttonCe.setForeground(new Color(255, 0, 0));
  buttonC = new JButton("C");
  buttonC.setForeground(new Color(255, 0, 0));
  buttonBk.addActionListener(this);
  buttonCe.addActionListener(this);
  buttonC.addActionListener(this);
  panel1.add(panel2, BorderLayout.NORTH);
  panel2.setLayout(new FlowLayout(FlowLayout.RIGHT));
  panel2.add(textMemory);
  panel2.add(labelMemSpace);
  panel2.add(buttonBk);
  panel2.add(buttonCe);
  panel2.add(buttonC);
  panel3 = new JPanel();
  panel1.add(panel3, BorderLayout.CENTER);
  button = new JButton[10];
  for (int i = 0; i < button.length; i++) {
   button[i] = new JButton(Integer.toString(i));
   button[i].setForeground(new Color(0, 0, 255));
  }
  buttonMC = new JButton("MC");
  buttonMC.setForeground(new Color(255, 0, 0));
  buttonMR = new JButton("MR");
  buttonMR.setForeground(new Color(255, 0, 0));
  buttonMS = new JButton("MS");
  buttonMS.setForeground(new Color(255, 0, 0));
  buttonMAdd = new JButton("M+");
  buttonMAdd.setForeground(new Color(255, 0, 0));
  buttonDot = new JButton(".");
  buttonDot.setForeground(new Color(0, 0, 255));
  buttonAddAndSub = new JButton("+/-");
  buttonAddAndSub.setForeground(new Color(0, 0, 255));
  buttonAdd = new JButton("+");
  buttonAdd.setForeground(new Color(255, 0, 0));
  buttonSub = new JButton("-");
  buttonSub.setForeground(new Color(255, 0, 0));
  buttonMul = new JButton("*");
  buttonMul.setForeground(new Color(255, 0, 0));
  buttonDiv = new JButton("/");
  buttonDiv.setForeground(new Color(255, 0, 0));
  buttonMod = new JButton("%");
  buttonMod.setForeground(new Color(0, 0, 255));
  buttonSqrt = new JButton("sqrt");
  buttonSqrt.setForeground(new Color(0, 0, 255));
  buttonDao = new JButton("1/x");
  buttonDao.setForeground(new Color(0, 0, 255));
  buttonEqual = new JButton("=");
  buttonEqual.setForeground(new Color(255, 0, 0));
  //將所有行為與監聽綁定
  panel3.setLayout(new GridLayout(4, 6));
  panel3.add(buttonMC);
  buttonMC.addActionListener(this);
  panel3.add(button[7]);
  button[7].addActionListener(this);
  panel3.add(button[8]);
  button[8].addActionListener(this);
  panel3.add(button[9]);
  button[9].addActionListener(this);
  panel3.add(buttonDiv);
  buttonDiv.addActionListener(this);
  panel3.add(buttonSqrt);
  buttonSqrt.addActionListener(this);
  panel3.add(buttonMR);
  buttonMR.addActionListener(this);
  panel3.add(button[4]);
  button[4].addActionListener(this);
  panel3.add(button[5]);
  button[5].addActionListener(this);
  panel3.add(button[6]);
  button[6].addActionListener(this);
  panel3.add(buttonMul);
  buttonMul.addActionListener(this);
  panel3.add(buttonMod);
  buttonMod.addActionListener(this);
  panel3.add(buttonMS);
  buttonMS.addActionListener(this);
  panel3.add(button[1]);
  button[1].addActionListener(this);
  panel3.add(button[2]);
  button[2].addActionListener(this);
  panel3.add(button[3]);
  button[3].addActionListener(this);
  panel3.add(buttonSub);
  buttonSub.addActionListener(this);
  panel3.add(buttonDao);
  buttonDao.addActionListener(this);
  panel3.add(buttonMAdd);
  buttonMAdd.addActionListener(this);
  panel3.add(button[0]);
  button[0].addActionListener(this);
  panel3.add(buttonAddAndSub);
  buttonAddAndSub.addActionListener(this);
  panel3.add(buttonDot);
  buttonDot.addActionListener(this);
  panel3.add(buttonAdd);
  buttonAdd.addActionListener(this);
  panel3.add(buttonEqual);
  buttonEqual.addActionListener(this);
  frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
  frame.pack();
  frame.show();
 }
 //設置各個按鈕行為
 public void actionPerformed(ActionEvent event) {
  boolean sign = false; //判斷是否是double型數參與運算,是為true,不是為false
  Object temp = event.getSource();
  try {
   //如果按下數據按鈕,將按下的按鈕代表的數據插入的當前文本框字符串之後
   for (int i = 0; i <= 9; i++)
    if (temp == button[i] && clickable == true)
     textAnswer.setText(textAnswer.getText() + Integer.toString(i));
     //按下'.'按鈕時,判斷當前文本框內字符串中含不含'.',如果已含,則不允許再插入'.'
   if (temp == buttonDot && clickable == true) {
    boolean isDot = false;
    if (textAnswer.getText().length() == 0)
     isDot = true;
    for (int i = 0; i < textAnswer.getText().length(); i++)
     if ('.' == textAnswer.getText().charAt(i)) {
      isDot = true;
      break;
     }
    if (isDot == false)
     textAnswer.setText(textAnswer.getText() + ".");
   }
   if ( (temp == buttonAdd || temp == buttonSub || temp == buttonMul ||
      temp == buttonDiv) && clickable == true) {
    //'+'操作
    if (temp == buttonAdd) {
     switch (prekey) {
      case 0:
       answerd += Double.parseDouble(textAnswer.getText());
       break;
      case 1:
       answerd -= Double.parseDouble(textAnswer.getText());
       break;
      case 2:
       answerd *= Double.parseDouble(textAnswer.getText());
       break;
      case 3:
       if (Double.parseDouble(textAnswer.getText()) == 0) {
        textAnswer.setText("除數不能為零");
        clickable = false;
       }
       else
        answerd /= Double.parseDouble(textAnswer.getText());
       break;
      default:
       answerd = Double.parseDouble(textAnswer.getText());
     }
     textAnswer.setText("");
     prekey = key = 0;
    }
    //'-'操作
    if (temp == buttonSub) {
     switch (prekey) {
      case 0:
       answerd += Double.parseDouble(textAnswer.getText());
       break;
      case 1:
       answerd -= Double.parseDouble(textAnswer.getText());
       break;
      case 2:
       answerd *= Double.parseDouble(textAnswer.getText());
       break;
      case 3:
       if (Double.parseDouble(textAnswer.getText()) == 0) {
        textAnswer.setText("除數不能為零");
        clickable = false;
       }
       else
        answerd /= Double.parseDouble(textAnswer.getText());
       break;
      default:
       answerd = Double.parseDouble(textAnswer.getText());
     }
     textAnswer.setText("");
     prekey = key = 1;
    }
    //'*'操作
    if (temp == buttonMul) {
     switch (prekey) {
      case 0:
       answerd += Double.parseDouble(textAnswer.getText());
       break;
      case 1:
       answerd -= Double.parseDouble(textAnswer.getText());
       break;
      case 2:
       answerd *= Double.parseDouble(textAnswer.getText());
       break;
      case 3:
       if (Double.parseDouble(textAnswer.getText()) == 0) {
        textAnswer.setText("除數不能為零");
        clickable = false;
       }
       else
        answerd /= Double.parseDouble(textAnswer.getText());
       break;
      default:
       answerd = Double.parseDouble(textAnswer.getText());
     }
     textAnswer.setText("");
     prekey = key = 2;
    }
    //'/'操作
    if (temp == buttonDiv) {
     switch (prekey) {
      case 0:
       answerd += Double.parseDouble(textAnswer.getText());
       break;
      case 1:
       answerd -= Double.parseDouble(textAnswer.getText());
       break;
      case 2:
       answerd *= Double.parseDouble(textAnswer.getText());
       break;
      case 3:
       if (Double.parseDouble(textAnswer.getText()) == 0) {
        textAnswer.setText("除數不能為零");
        clickable = false;
       }
       else
        answerd /= Double.parseDouble(textAnswer.getText());
       break;
      default:
       answerd = Double.parseDouble(textAnswer.getText());
     }
     textAnswer.setText("");
     prekey = key = 3;
    }
   }
   //'='操作
   if (temp == buttonEqual && clickable == true) {
    //如果連續按'=',則進行連續運算
    if (prekey == 5) {
     if (key == 0) {
      answerd += vard;
      textAnswer.setText(df.format(answerd));
     }
     if (key == 1) {
      answerd -= vard;
      textAnswer.setText(df.format(answerd));
     }
     if (key == 2) {
      answerd *= vard;
      textAnswer.setText(df.format(answerd));
     }
     if (key == 3) {
      if (Double.parseDouble(textAnswer.getText()) == 0) {
       textAnswer.setText("除數不能為零");
       clickable = false;
      }
      else {
       answerd /= vard;
       textAnswer.setText(df.format(answerd));
      }
     }
    }
    else {
     vard = Double.parseDouble(textAnswer.getText());
     if (key == 0) {
      prekey = -1;
      answerd += Double.parseDouble(textAnswer.getText());
      textAnswer.setText(df.format(answerd));
     }
     if (key == 1) {
      prekey = -1;
      answerd -= Double.parseDouble(textAnswer.getText());
      textAnswer.setText(df.format(answerd));
     }
     if (key == 2) {
      prekey = -1;
      answerd *= Double.parseDouble(textAnswer.getText());
      textAnswer.setText(df.format(answerd));
     }
     if (key == 3) {
      prekey = -1;
      if (Double.parseDouble(textAnswer.getText()) == 0) {
       textAnswer.setText("除數不能為零");
       clickable = false;
      }
      else {
       answerd /= Double.parseDouble(textAnswer.getText());
       textAnswer.setText(df.format(answerd));
      }
     }
    }
    prekey = 5;
   }
   //'%'操作,對第二個操作數除以100
   if (temp == buttonMod && clickable == true) {
    if (answerd == 0) {
     String s = textAnswer.getText();
     textAnswer.setText(s);
    }
    else {
     boolean isDot = false;
     for (int i = 0; i < textAnswer.getText().length(); i++)
      if ('.' == textAnswer.getText().charAt(i)) {
       isDot = true;
       break;
      }
     //如果是double數,除100
     if (isDot == true) {
      double dtemp = Double.parseDouble(textAnswer.getText());
      dtemp = dtemp / 100.0;
      textAnswer.setText(Double.toString(dtemp));
     }
     else {
      //如果是int數但能被100整除,則去掉末尾兩個零
      if (Integer.parseInt(textAnswer.getText()) % 100 == 0) {
       int itemp = Integer.parseInt(textAnswer.getText());
       itemp /= 100;
       textAnswer.setText(Integer.toString(itemp));
      }
      //如果是int數,但不能被100整除,則按double數處理
      else {
       double dtemp = Double.parseDouble(textAnswer.getText());
       dtemp = dtemp / 100.0;
       textAnswer.setText(Double.toString(dtemp));
      }
     }
    }
   }
   //開根號運算
   if (temp == buttonSqrt && clickable == true) {
    String s = textAnswer.getText();
    if (s.charAt(0) == '-') {
     textAnswer.setText("負數不能開根號");
     clickable = false;
    }
    else
     textAnswer.setText(Double.toString(java.lang.Math.sqrt(Double.
       parseDouble(textAnswer.getText()))));
   }
   //倒數運算
   if (temp == buttonDao && clickable == true) {
    if (textAnswer.getText().charAt(0) == '0' &&
      textAnswer.getText().length() == 1) {
     textAnswer.setText("零不能求倒數");
     clickable = false;
    }
    else {
     boolean isDec = true;
     int i, j, k;
     String s = Double.toString(1 / Double.parseDouble(textAnswer.getText()));
     for (i = 0; i < s.length(); i++)
      if (s.charAt(i) == '.')
       break;
     for (j = i + 1; j < s.length(); j++)
      if (s.charAt(j) != '0') {
       isDec = false;
       break;
      }
     if (isDec == true) {
      String stemp = "";
      for (k = 0; k < i; k++)
       stemp += s.charAt(k);
      textAnswer.setText(stemp);
     }
     else
      textAnswer.setText(s);
    }
   }
   //按下'+/-'按鈕時處理
   if (temp == buttonAddAndSub && clickable == true) {
    boolean isNumber = true;
    String s = textAnswer.getText();
    for (int i = 0; i < s.length(); i++)
     if (! (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.' ||
         s.charAt(i) == '-')) {
      isNumber = false;
      break;
     }
    if (isNumber == true) {
     //如果當前字符串首字母有'-'號,代表現在是個負數,再按下時,則將首符號去掉
     if (s.charAt(0) == '-') {
      textAnswer.setText("");
      for (int i = 1; i < s.length(); i++) {
       char a = s.charAt(i);
       textAnswer.setText(textAnswer.getText() + a);
      }
     }
     //如果當前字符串第一個字符不是符號,則添加一個符號在首字母處
     else
      textAnswer.setText('-' + s);
    }
   }
   //計算器有關內存操作
   //'MC'的操作,將內存清0
   if (temp == buttonMC && clickable == true) {
    memoryd = memoryi = 0;
    textMemory.setText("");
   }
   //'MS'的操作,將當前文本框內容保存入內存,顯示'M'
   if (temp == buttonMS && clickable == true) {
    boolean isDot = false;
    textMemory.setText("  M");
    for (int i = 0; i < textAnswer.getText().length(); i++)
     if ('.' == textAnswer.getText().charAt(i)) {
      isDot = true;
      break;
     }
    //如果是double,則存入memoryd(double存儲器)
    if (isDot == true) {
     memoryd = Double.parseDouble(textAnswer.getText());
     memoryi = 0; //保證存儲器中存放最新的值
    }
    //如果是int,則存入memoryi(int存儲器)
    else {
     memoryi = Integer.parseInt(textAnswer.getText());
     memoryd = 0; //保證存儲器中存放最新的值
    }
   }
   //'MR'的操作,將存儲器中的信息輸出
   if (temp == buttonMR && clickable == true) {
    if (memoryd != 0)
     textAnswer.setText(Double.toString(memoryd));
    if (memoryi != 0)
     textAnswer.setText(Integer.toString(memoryi));
   }
   //'M+'的功能,將當前文本框裡的數據和存儲器中數據相加後,再存入存儲器
   if (temp == buttonMAdd && clickable == true) {
    boolean isDot = false;
    for (int i = 0; i < textAnswer.getText().length(); i++)
     if ('.' == textAnswer.getText().charAt(i)) {
      isDot = true;
      break;
     }
    if (memoryi != 0) { //存儲中是一個int型數
     if (isDot == false) //被加數是一個int型數---www.bianceng.cn
      memoryi += Integer.parseInt(textAnswer.getText());
     else { //被加數是一個double型數,則將int存儲器中數傳入double存儲器與當前數相加,int存儲器清零
      memoryd = memoryi + Double.parseDouble(textAnswer.getText());
      memoryi = 0;
     }
    }
    else
     memoryd += Double.parseDouble(textAnswer.getText());
   }
   //按下'Backspace'鍵,利用循環將當前字符串中的最後一個字母刪除
   if (temp == buttonBk && clickable == true) {
    String s = textAnswer.getText();
    textAnswer.setText("");
    for (int i = 0; i < s.length() - 1; i++) {
     char a = s.charAt(i);
     textAnswer.setText(textAnswer.getText() + a);
    }
   }
   //按下'CE'按鈕,將當前文本框內數據清除
   if (temp == buttonCe) {
    textAnswer.setText("");
    clickable = true;
   }
   //按下'C'按鈕,文本框內數據清除,同時var,answer清0
   if (temp == buttonC) {
    vard = answerd = 0;
    textAnswer.setText("");
    clickable = true;
   }
   //按下'復制'菜單欄
   if (temp == copyItem) {
    copy = textAnswer.getText();
   }
   //按下'粘貼'菜單欄
   if (temp == pasteItem) {
    textAnswer.setText(copy);
   }
   if (temp == sItem) {
    JOptionPane.showMessageDialog(panel, "當前是標准型計算器,\n科學型計算器有待更新。");
   }
   //按下'幫助主題'菜單欄
   if (temp == topHelp) {
    JOptionPane.showMessageDialog(panel, scrollHelp);
   }
   //按下'數字分組'菜單欄
   if (temp == numberGroup) {
    if (numberGroup.getText().compareTo("  數字分組(I)") == 0)
     numberGroup.setText("√數字分組(I)");
    else
     numberGroup.setText("  數字分組(I)");
   }
   //按下'關於'菜單欄
   if (temp == aboutCal) {
    JOptionPane.showMessageDialog(panel, "計算器1.00版\n開發者:樓競");
   }
  }
  //輸入中如果有操作非法,比如按下兩次'+',捕獲異常
  catch (Exception e) {
   textAnswer.setText("操作非法");
   clickable = false;
  }
 }
 //主函數
 public static void main(String args[]) {
  new Calculator();
 }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved