자바 계산기 설계 실현
수요 분석
4.567917.목적 은 자바 기반 의 괄호 를 풀 고 곱 하기 식 을 줄 일 수 있 는 인터페이스 가 있 는 계산 기 를 실현 하 는 것 이다
1.자바 계산기 인터페이스 클래스 구현
2.자바 컴 퓨 팅 대괄호 가감 승제 표현 식 의 클래스 구현
3.주 함수 호출 실현
설계 실현
Java 계산기 프로젝트 구조:
 
 Calculator 류 는 계산기 인터페이스 디자인 이 고 Calculate 류 는 괄호 가 있 는 가감 곱 하기 표현 식 의 클래스 이 며 Main 함 수 는 프로젝트 프로그램의 입구 입 니 다.
자바 계산기 인터페이스 디자인 구현 코드:
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
     
  }  
 }
*/
}
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();
 }
} 
 확대 인터페이스 를 마음대로 축소 할 수 있 고 인터페이스 부품 은 인터페이스 크기 에 따라 스스로 조정 할 수 있다.
기타 기능
현 재 는 표준 형 계산 을 실 현 했 고 과학 형 계산 이 더욱 복잡 하 며 인터페이스 가 실현 되 었 으 며 계산 기능 이 없 으 며 추 후 계속 개발 할 수 있 으 니 기대 하 시기 바 랍 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.