Java计算器代码

来源:互联网 发布:网络数据传输结构 编辑:程序博客网 时间:2024/06/05 02:47


首先写了个简单的界面如下:



整个面板用了BorderLayout布局,分为北,左和中。中部采用网格布局。定义这个类为CalFrame.java:

[java] view plain copy
  1. package calframe;  
  2.   
  3. import java.awt.BorderLayout;  
  4. import java.awt.Color;  
  5. import java.awt.Dimension;  
  6. import java.awt.GridLayout;  
  7. import java.awt.event.ActionEvent;  
  8. import java.awt.event.ActionListener;  
  9. import java.util.Arrays;  
  10.   
  11. import javax.swing.JButton;  
  12. import javax.swing.JFrame;  
  13. import javax.swing.JPanel;  
  14. import javax.swing.JTextField;  
  15.   
  16. public class CalFrame extends JFrame {  
  17.     /** 
  18.      * 计算器的外观设计 
  19.      */  
  20.     private static final long serialVersionUID = 1L;  
  21.     private final static int PRE_WIDTH = 500;  
  22.     private final static int PRE_HEIGHT = 400;  
  23.       
  24.     private JTextField text = null;  
  25.     private JButton button = null//存储标记  
  26.       
  27.     private String[] nOp = {"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};  
  28.     private String[] mOp = {"MC","MR","MS","M+"};  
  29.     private String[] rOp = {"Back","CE","C"};  
  30.     private CalService service = new CalService();  
  31.       
  32.     public CalFrame(){  
  33.         this.setTitle("计算器");  
  34.         this.setSize(PRE_WIDTH, PRE_HEIGHT);  
  35.         this.setLocationRelativeTo(null);  
  36.         this.setResizable(false);  
  37.           
  38.         //添加底层   
  39.         JPanel panel = new JPanel();  
  40.         panel.setLayout(new BorderLayout(10,1));  
  41.         panel.add(getTextField(), BorderLayout.NORTH);  
  42.         panel.setPreferredSize(new Dimension(PRE_WIDTH, PRE_HEIGHT));  
  43.           
  44.         //WEST  
  45.         JButton[] mButton = getMButton();  
  46.         JPanel panel1 = new JPanel();  
  47.         panel1.setLayout(new GridLayout(5,1,0,5));  
  48.         for(JButton b : mButton ){  
  49.             panel1.add(b);  
  50.         }  
  51.         panel.add(panel1,BorderLayout.WEST);  
  52.         //  
  53.         JButton[] rButton = getRButton();  
  54.         JPanel panel2 = new JPanel();  
  55.         panel2.setLayout(new BorderLayout(1,5));  
  56.         JPanel panel21 = new JPanel();  
  57.         panel21.setLayout(new GridLayout(1,3,3,3));  
  58.         for(JButton b : rButton){  
  59.             panel21.add(b);  
  60.         }  
  61.         panel2.add(panel21,BorderLayout.NORTH);  
  62.           
  63.         JButton[] nButton = getNButton();  
  64.         JPanel panel22 = new JPanel();  
  65.         panel22.setLayout(new GridLayout(4,5,3,5));  
  66.         for(JButton b : nButton){  
  67.             panel22.add(b);  
  68.         }  
  69.         panel2.add(panel22,BorderLayout.CENTER);  
  70.         panel.add(panel2,BorderLayout.CENTER);  
  71.           
  72.         this.add(panel);  
  73.         this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
  74.         this.setVisible(true);  
  75.   
  76.           
  77.     }  
  78.     //返回显示框  
  79.     private JTextField getTextField(){  
  80.         text = new JTextField("0",10);  
  81.         //text.setSize(480, 50);  
  82.         return text;  
  83.     }  
  84.     //返回数字键  
  85.     private JButton[] getNButton(){  
  86.         String[] redButton = {"/","*","-","+","="};  
  87.         JButton[] nbutton = new JButton[nOp.length];  
  88.         for(int i = 0; i < this.nOp.length; i++){  
  89.             JButton b = new JButton(this.nOp[i]);  
  90.             b.addActionListener(getActionListener());  
  91.               
  92.             Arrays.sort(redButton);  
  93.             if(Arrays.binarySearch(redButton, nOp[i]) >= 0){  
  94.                 b.setForeground(Color.red);  
  95.             }else{  
  96.                 b.setForeground(Color.blue);  
  97.             }  
  98.             nbutton[i] = b;  
  99.         }  
  100.         return nbutton;  
  101.     }  
  102.     //返回操作健  
  103.     private JButton[] getMButton(){  
  104.         JButton[] mbutton = new JButton[mOp.length + 1];  
  105.         mbutton[0] = getButton();  
  106.         for(int i = 0; i < this.mOp.length; i++){  
  107.             JButton b = new JButton(this.mOp[i]);  
  108.             b.addActionListener(getActionListener());  
  109.             b.setForeground(Color.red);  
  110.             mbutton[i+1] = b;  
  111.         }  
  112.         return mbutton;  
  113.     }  
  114.     private JButton[] getRButton(){  
  115.         JButton[] rbutton = new JButton[rOp.length];  
  116.         for(int i = 0; i < this.rOp.length; i++){  
  117.             JButton b = new JButton(this.rOp[i]);  
  118.             b.addActionListener(getActionListener());  
  119.             b.setForeground(Color.red);  
  120.             rbutton[i] = b;  
  121.         }  
  122.         return rbutton;  
  123.     }  
  124.     private JButton getButton(){  
  125.         button = new JButton();  
  126.         return button;  
  127.     }  
  128.     private ActionListener getActionListener(){  
  129.         ActionListener actionListener = new ActionListener() {  
  130.               
  131.             @Override  
  132.             public void actionPerformed(ActionEvent e) {  
  133.                 String cmd = e.getActionCommand();  
  134.                 String result = null;  
  135.                 try {  
  136.                     result = service.callMethod(cmd, text.getText());  
  137.                 } catch (Exception e2) {  
  138.                     System.out.println(e2.getMessage());  
  139.                 }  
  140.                 if(cmd.indexOf("MC") == 0){  
  141.                     button.setText("");  
  142.                 }else if(cmd.indexOf("M") == 0){  
  143.                     button.setText("M");  
  144.                 }  
  145.                 //显示计算结果  
  146.                 if(result != null){  
  147.                     text.setText(result);  
  148.                 }  
  149.               
  150.             }  
  151.         };   
  152.         return actionListener;  
  153.     }  
  154.     public static void main(String[] args) {  
  155.         new CalFrame();  
  156.     }  
  157. }  

接着实现几个基本的操作,加,减,乘,除。考虑到精度和范围的问题,我们定义了一个MyMath类,数据格式都使用BigDecimal对象进行计算。MyMath.java:

[java] view plain copy
  1. package calframe;  
  2.   
  3. import java.math.BigDecimal;  
  4.   
  5. public class MyMath {  
  6.     /** 
  7.      * 为一个double类型创建BigDecimal对象 
  8.      */  
  9.     private static BigDecimal getBigDecimal(double number){  
  10.         return new BigDecimal(number);  
  11.     }  
  12.     public static double add(double num1, double num2) {  
  13.         BigDecimal first = getBigDecimal(num1);  
  14.         BigDecimal second = getBigDecimal(num2);  
  15.         return first.add(second).doubleValue();  
  16.     }  
  17.     public static double subtract(double num1, double num2) {  
  18.         BigDecimal first = getBigDecimal(num1);  
  19.         BigDecimal second = getBigDecimal(num2);  
  20.         return first.subtract(second).doubleValue();  
  21.     }     
  22.     public static double multiply(double num1, double num2) {  
  23.         BigDecimal first = getBigDecimal(num1);  
  24.         BigDecimal second = getBigDecimal(num2);  
  25.         return first.multiply(second).doubleValue();  
  26.     }     
  27.     public static double divide(double num1, double num2) {  
  28.         BigDecimal first = getBigDecimal(num1);  
  29.         BigDecimal second = getBigDecimal(num2);  
  30.         return first.divide(second,3,BigDecimal.ROUND_HALF_UP).doubleValue();  
  31.     }  
  32. }  

最后处理按钮的事件,我们定义了一个CalService类处理业务逻辑:

[java] view plain copy
  1. package calframe;  
  2.   
  3. public class CalService {  
  4.     private boolean isSecondNum = false;  
  5.     private String lastOp;  
  6.     private String firstNum = "0";  
  7.     private String secondNum = "null";  
  8.     private double store;  
  9.     private String numString = "0123456789.";  
  10.     private String opString = "+-*/";  
  11.   
  12.     public String catNum(String cmd, String text) {  
  13.         String result = cmd;  
  14.         // 如果text不等于0  
  15.         if (!"0".equals(text)) {  
  16.             if (isSecondNum) {  
  17.                 isSecondNum = false;  
  18.             } else {  
  19.                 result = text + cmd;  
  20.             }  
  21.         }  
  22.         if (result.indexOf(".") == 0) {  
  23.             result = "0" + result;  
  24.         }  
  25.         return result;  
  26.     }  
  27.   
  28.     public String setOp(String cmd, String text) {  
  29.         this.lastOp = cmd;  
  30.         this.firstNum = text;  
  31.         this.secondNum = null;  
  32.   
  33.         this.isSecondNum = true;  
  34.         return null;  
  35.     }  
  36.   
  37.     public String cal(String text, boolean isPercent) {  
  38.         double secondResult = secondNum == null ? Double.valueOf(text)  
  39.                 .doubleValue() : Double.valueOf(secondNum).doubleValue();  
  40.                   
  41.         //除数为0  
  42.         if(secondResult == 0 && this.lastOp.equals("/")){  
  43.             return "0";  
  44.         }  
  45.           
  46.         //有%  
  47.         if(isPercent){  
  48.             secondResult = MyMath.multiply(Double.valueOf(firstNum), MyMath.divide(secondResult, 100));  
  49.         }  
  50.         if(this.lastOp.equals("+")){  
  51.             firstNum = String.valueOf(MyMath.add(Double.valueOf(firstNum),secondResult));  
  52.         }else if (this.lastOp.equals("-")) {  
  53.             firstNum = String.valueOf(MyMath.subtract(Double.valueOf(firstNum),secondResult));  
  54.         }else if (this.lastOp.equals("*")) {  
  55.             firstNum = String.valueOf(MyMath.multiply(Double.valueOf(firstNum),secondResult));  
  56.         }else if (this.lastOp.equals("/")) {  
  57.             firstNum = String.valueOf(MyMath.divide(Double.valueOf(firstNum),secondResult));  
  58.         }  
  59.           
  60.         secondNum = secondNum == null ? text :secondNum;  
  61.         this.isSecondNum = true;  
  62.         return firstNum;  
  63.     }  
  64.     //求开方  
  65.     public String sqrt(String text){  
  66.         this.isSecondNum = true;  
  67.         return String.valueOf(Math.sqrt(Double.valueOf(text)));  
  68.     }  
  69.     //求倒数  
  70.     public String setReciprocal(String text){  
  71.         if (text.equals("0")){  
  72.             return text;  
  73.         }else{  
  74.             this.isSecondNum = true;  
  75.             return String.valueOf(MyMath.divide(1, Double.valueOf(text)));  
  76.         }  
  77.     }  
  78.     //存储  
  79.     public String mCmd(String cmd,String text){  
  80.         if(cmd.equals("M+")){  
  81.             store = MyMath.add(store, Double.valueOf(text));  
  82.         }else if (cmd.equals("MC")) {  
  83.             store = 0;  
  84.         }else if (cmd.equals("MR")) {  
  85.             isSecondNum = true;  
  86.             return String.valueOf(store);  
  87.         }else if (cmd.equals("MS")) {  
  88.             store = Double.valueOf(text).doubleValue();  
  89.         }  
  90.         return null;  
  91.     }  
  92.       
  93.     public String backSpace(String text){  
  94.         return text.equals("0") || text.equals("") ? "0" :text.substring(0,text.length()-1);  
  95.     }  
  96.       
  97.     public String setNegative(String text){  
  98.         if(text.indexOf("-") == 0){  
  99.             return text.substring(1,text.length());  
  100.         }else{  
  101.             return "-" + text;  
  102.         }  
  103.     }  
  104.     public String clearAll(){  
  105.         this.firstNum = "0";  
  106.         this.secondNum = null;  
  107.         return this.firstNum;  
  108.     }  
  109.     public String clear(String text){  
  110.         return "0";  
  111.     }  
  112.       
  113.     public String callMethod(String cmd, String text){  
  114.         if(cmd.equals("C")){  
  115.             return clearAll();  
  116.         }else if(cmd.equals("CE")){  
  117.             return clear(text);  
  118.         }else if (cmd.equals("Back")) {  
  119.             return backSpace(text);  
  120.         }else if (numString.indexOf(cmd) != -1) {  
  121.             return catNum(cmd, text);  
  122.         }else if (opString.indexOf(cmd) != -1) {  
  123.             return setOp(cmd, text);  
  124.         }else if (cmd.equals("+/-")) {  
  125.             return setNegative(text);  //设置正负号  
  126.         }else if(cmd.equals("1/x")){  
  127.             return setReciprocal(text);  
  128.         }else if (cmd.equals("sqrt")) {  
  129.             return sqrt(text);  
  130.         }else if(cmd.equals("%")){  
  131.             return cal(text, true);  
  132.         }else if(cmd.equals("=")){  
  133.             return cal(text, false);  
  134.         }else {  
  135.             return mCmd(cmd, text);  
  136.         }  
  137.     }  
  138. }  
最后的calMethod方法大量使用if else判断不是好的实现方法,感兴趣的可以看看java的设计模式,消除这样的判断。
至此,一个简易的计算器就完成了。欢迎大家给为留言,共同学习,共同进步。
原创粉丝点击