Java實現計算器設計

本文實例為大傢分享瞭Java實現計算器設計的具體代碼,供大傢參考,具體內容如下

需求分析

  • 目的是實現一個基於Java的可以求解帶括號加減乘除表達式帶界面的計算器。
  • 需要知道的Java技術:Java Swing(Java圖形界面設計)、Java集合(棧)、lambda表達式、Java基礎等。

設計思路

1、實現一個Java計算器界面類
2、實現一個Java計算帶括號加減乘除表達式的類
3、實現主函數調用

設計實現

Java計算器項目結構:

Calculator類為計算器界面設計、Calculate類為計算帶括號加減乘除表達式的類,Main函數為項目程序入口。

Java計算器界面設計實現代碼:

package Calculator;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculator extends JFrame{
  
 private double result=0;
 private int count=0;
 
 public Calculator() {
  this.setSize(330,399);  
  this.setTitle("計算器");  
  init();
//  this.pack();
  this.setVisible(true);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
 }
 
 public void init() {//初始化界面
  
  this.setLayout(new BorderLayout()); //總體佈局為邊框式佈局
  
  /*
   * 總體邊框式佈局north放置文本框
   */  
  JTextField textField=new JTextField();
  textField.disable();
  textField.setPreferredSize(new Dimension(this.getWidth(),50));
  this.add(textField,BorderLayout.NORTH);

  /* 
   * 總體邊框式佈局center放置@panel(邊框式佈局)
   * @panel邊框式佈局north放置@panelN(網格佈局)
   * @panel邊框式佈局center放置@panelC(卡片式佈局)
   * @panelC卡片來切換@panel0(標準)和@panel1(科學)兩種模式
   * @panel0,@panel1均為網格佈局
   */     
  JPanel panel=new JPanel();
  panel.setLayout(new BorderLayout());
  this.add(panel, BorderLayout.CENTER);
  
  JPanel panelN=new JPanel();
  panelN.setLayout(new GridLayout(1,6));
  JButton MC=new JButton("MC");
  JButton MR=new JButton("MR");
  JButton M0=new JButton("M+");
  JButton M1=new JButton("M-");
  JButton MS=new JButton("MS");
  JButton M=new JButton("M");
  panelN.add(MC);panelN.add(MR);panelN.add(M0);
  panelN.add(M1);panelN.add(MS);panelN.add(M);
  panel.add(panelN,BorderLayout.NORTH);
  
  CardLayout cardLayout=new CardLayout();
  JPanel panelC=new JPanel();
  panelC.setLayout(cardLayout);
  
  JPanel panel0=new JPanel();
  panel0.setLayout(new GridLayout(6,4));
  JButton[] standredButton=new JButton[24];
  String str[]={"%","√","x²","1/x",
    "CE","C","×","/",
    "7","8","9","*",
    "4","5","6","-",
    "1","2","3","+",
    "±","0",".","=" 
  };
  for(int i=0;i<standredButton.length;i++) {
   standredButton[i]=new JButton(str[i]);
   String text=standredButton[i].getText();
   standredButton[i].addActionListener(new ActionListener() {
    
    @Override
    public void actionPerformed(ActionEvent e) {
     // TODO Auto-generated method stub
     if(text.equals("CE")||text.equals("C")) {
      textField.setText("");
     }
     else if(text.equals("=")) {
      String expression=textField.getText();
      Calculate cal=new Calculate();
      textField.setText(cal.evaluateExpression(expression)+"");
     }
     else if(text.equals("%")) {
      
     }
     else if(text.equals("√")) {
      result=Double.parseDouble(textField.getText());
      result=Math.sqrt(result);
      textField.setText(result+"");
     }
     else if(text.equals("x²")) {
      result=Double.parseDouble(textField.getText());
      result*=result;
      textField.setText(result+"");
     }
     else if(text.equals("1/x")) {
      result=Double.parseDouble(textField.getText());
      result=1/result;
      textField.setText(result+"");
     }
     else if(text.equals("±")) {
      if(count==0) {
       textField.setText(textField.getText()+"-");
       count=1;
      }
      else {
       textField.setText(textField.getText()+"+");
       count=0;
      }
     }
     else if(text.equals("×")) {
      textField.setText(textField.getText().substring(0, textField.getText().length()-1));
     }
     else {
      textField.setText(textField.getText()+text);
     }
         
    }
    
   }
   
   );
   panel0.add(standredButton[i]);
  }
  panelC.add(panel0);
  
  JPanel panel1=new JPanel();
  panel1.setLayout(new GridLayout(7,5));
  JButton scienceButton[]=new JButton[35];
  String str1[]= {
  "x²","x^y","sin","cos","tan",
  "√","10^x","log","Exp","Mod",
  "↑","CE","C","×","/",
  "π","7","8","9","*",
  "n!","4","5","6","-",
  "±","1","2","3","+",
  "(",")","0",".","="    
  };
  for(int i=0;i<str1.length;i++) {
   scienceButton[i]=new JButton(str1[i]);
   //scienceButton[i].addActionListener();
   panel1.add(scienceButton[i]);
  }
  panelC.add(panel1);
   
  panel.add(panelC,BorderLayout.CENTER);
  
  /*
   * 菜單 
   */
  JMenuBar menuBar=new JMenuBar();
  this.setJMenuBar(menuBar);
  JMenu modelMenu=new JMenu("模式");
  menuBar.add(modelMenu);
  JMenuItem standred=new JMenuItem("標準");  
  standred.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    cardLayout.first(panelC);
   }  
  });
  modelMenu.add(standred);
  JMenuItem science=new JMenuItem("科學");
  science.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    cardLayout.last(panelC);
   }   
  });
  modelMenu.add(science);
  
 }
/*
 private class ButtonAction implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent e) {
   // TODO Auto-generated method stub
     
  }  
 }
*/
}

Java計算帶括號加減乘除表達式類的實現:

package Calculator;

import java.util.*;

/*
*使用此類直接調用evaluateExpression方法即可,傳入需計算的表達式,返回計算結果
*/
public class Calculate {
    //這個函數的作用就是使用空格分割字符串,以便後面使用分割函數使得將字符串分割成數組
    public String insetBlanks(String s) {
        String result = "";
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(' || s.charAt(i) == ')' ||
                    s.charAt(i) == '+' || s.charAt(i) == '-'
                    || s.charAt(i) == '*' || s.charAt(i) == '/')
                result += " " + s.charAt(i) + " ";
            else
                result += s.charAt(i);
        }
        return result;
    }

    public double evaluateExpression(String expression) {
        Stack<Double> operandStack = new Stack<>();
        Stack<Character> operatorStack = new Stack<>();
        expression = insetBlanks(expression);
        String[] tokens = expression.split(" ");
        for (String token : tokens) {
            if (token.length() == 0)   //如果是空格的話就繼續循環,什麼也不操作
                continue;
            //如果是加減的話,因為加減的優先級最低,因此這裡的隻要遇到加減號,無論操作符棧中的是什麼運算符都要運算
            else if (token.charAt(0) == '+' || token.charAt(0) == '-') {
                //當棧不是空的,並且棧中最上面的一個元素是加減乘除的人任意一個
                while (!operatorStack.isEmpty()&&(operatorStack.peek() == '-' || operatorStack.peek() == '+' || operatorStack.peek() == '/' || operatorStack.peek() == '*')) {
                    processAnOperator(operandStack, operatorStack);   //開始運算
                }
                operatorStack.push(token.charAt(0));   //運算完之後將當前的運算符入棧
            }
            //當前運算符是乘除的時候,因為優先級高於加減,因此要判斷最上面的是否是乘除,如果是乘除就運算,否則的話直接入棧
            else if (token.charAt(0) == '*' || token.charAt(0) == '/') {
                while (!operatorStack.isEmpty()&&(operatorStack.peek() == '/' || operatorStack.peek() == '*')) {
                    processAnOperator(operandStack, operatorStack);
                }
                operatorStack.push(token.charAt(0));   //將當前操作符入棧
            }
            //如果是左括號的話直接入棧,什麼也不用操作,trim()函數是用來去除空格的,由於上面的分割操作可能會令操作符帶有空格
            else if (token.trim().charAt(0) == '(') {
                operatorStack.push('(');
            }
            //如果是右括號的話,清除棧中的運算符直至左括號
            else if (token.trim().charAt(0) == ')') {
                while (operatorStack.peek() != '(') {
                    processAnOperator(operandStack, operatorStack);    //開始運算
                }
                operatorStack.pop();   //這裡的是運算完之後清除左括號
            }
            //這裡如果是數字的話直接如數據的棧
            else {
                operandStack.push(Double.parseDouble(token));   //將數字字符串轉換成數字然後壓入棧中
            }
        }
        //最後當棧中不是空的時候繼續運算,知道棧中為空即可
        while (!operatorStack.isEmpty()) {
            processAnOperator(operandStack, operatorStack);
        }
        return operandStack.pop();    //此時數據棧中的數據就是運算的結果
    }

    //這個函數的作用就是處理棧中的兩個數據,然後將棧中的兩個數據運算之後將結果存儲在棧中
    public void processAnOperator(Stack<Double> operandStack, Stack<Character> operatorStack) {
        char op = operatorStack.pop();  //彈出一個操作符
        Double op1 = operandStack.pop();  //從存儲數據的棧中彈出連個兩個數用來和操作符op運算
        Double op2 = operandStack.pop();
        if (op == '+')  //如果操作符為+就執行加運算
            operandStack.push(op1 + op2);
        else if (op == '-')
            operandStack.push(op2 - op1);   //因為這個是棧的結構,自然是上面的數字是後面的,因此用op2-op1
        else if (op == '*')
            operandStack.push(op1 * op2);
        else if (op == '/')
            operandStack.push(op2 / op1);
    }
}

主函數:

package Calculator;

public class Main {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Calculator calculator=new Calculator();
 }

}

設計實現展示

可以隨意縮小放大界面,界面部件會跟隨界面大小自適應調整。

其他功能

目前實現瞭標準型計算,科學型計算更加復雜,實現瞭界面,沒有計算功能,後續可能會繼續開發,敬請期待。

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: