码迷,mamicode.com
首页 > 其他好文 > 详细

一个很简陋的计算器

时间:2016-01-18 17:24:00      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

package com.imooc.calculator;

import java.util.ArrayList;
import java.util.Arrays;

import bsh.EvalError;
import bsh.Interpreter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {
    Button btn_0;
    Button btn_1;
    Button btn_2;
    Button btn_3;
    Button btn_4;
    Button btn_5;
    Button btn_6;
    Button btn_7;
    Button btn_8;
    Button btn_9;

    Button btn_point;// СÊýµã
    Button btn_divide;// ³ýÒÔ
    Button btn_multiply;// ³ËÒÔ
    Button btn_minus;// ¼õÈ¥
    Button btn_pluse;// ¼Ó
    Button btn_equal;// µÈÓÚ

    Button btn_clear;
    Button btn_del;

    EditText et_showview;
    boolean needclear;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_0 = (Button) findViewById(R.id.btn_0);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);
        btn_3 = (Button) findViewById(R.id.btn_3);
        btn_4 = (Button) findViewById(R.id.btn_4);
        btn_5 = (Button) findViewById(R.id.btn_5);
        btn_6 = (Button) findViewById(R.id.btn_6);
        btn_7 = (Button) findViewById(R.id.btn_7);
        btn_8 = (Button) findViewById(R.id.btn_8);
        btn_9 = (Button) findViewById(R.id.btn_9);
        btn_point = (Button) findViewById(R.id.btn_point);// СÊýµã
        btn_divide = (Button) findViewById(R.id.btn_divide);// ³ýÒÔ
        btn_multiply = (Button) findViewById(R.id.btn_multiply);// ³ËÒÔ
        btn_minus = (Button) findViewById(R.id.btn_minus);// ¼õÈ¥
        btn_pluse = (Button) findViewById(R.id.btn_pluse);// ¼Ó
        btn_equal = (Button) findViewById(R.id.btn_equal);// µÈÓÚ

        btn_clear = (Button) findViewById(R.id.btn_clear);
        btn_del = (Button) findViewById(R.id.btn_del);
        et_showview = (EditText) findViewById(R.id.et_showview);

        btn_0.setOnClickListener(this);
        btn_1.setOnClickListener(this);
        btn_2.setOnClickListener(this);
        btn_3.setOnClickListener(this);
        btn_4.setOnClickListener(this);
        btn_5.setOnClickListener(this);
        btn_6.setOnClickListener(this);
        btn_7.setOnClickListener(this);
        btn_8.setOnClickListener(this);
        btn_9.setOnClickListener(this);

        btn_point.setOnClickListener(this);
        btn_divide.setOnClickListener(this);
        btn_multiply.setOnClickListener(this);
        btn_minus.setOnClickListener(this);
        btn_pluse.setOnClickListener(this);
        btn_equal.setOnClickListener(this);

        btn_clear.setOnClickListener(this);
        btn_del.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String str = et_showview.getText().toString();
        switch (v.getId()) {
        case R.id.btn_0:
        case R.id.btn_1:
        case R.id.btn_2:
        case R.id.btn_3:
        case R.id.btn_4:
        case R.id.btn_5:
        case R.id.btn_6:
        case R.id.btn_7:
        case R.id.btn_8:
        case R.id.btn_9:
        case R.id.btn_point:
            if(needclear){
                str = "";
                et_showview.setText("");
            }
            et_showview.setText(str + ((Button) v).getText());
            break;
        case R.id.btn_pluse:
        case R.id.btn_minus:
        case R.id.btn_multiply:
        case R.id.btn_divide:
            if(needclear){
                et_showview.setText("");
            }
            et_showview.setText(str +" "+((Button) v).getText()+" ");
            break;
        case R.id.btn_equal:
            getResult();
            break;
        case R.id.btn_del:
            if (str != null && !str.equals("")) {
                et_showview.setText(str.substring(0, str.length() - 1));
            }
            break;
        case R.id.btn_clear:
            et_showview.setText("");
            break;
        }
    }

    /**
     * »ñÈ¡¼ÆËã½á¹û
     */
    private void getResult() {
        needclear = true;
        String exp = et_showview.getText().toString();
        double r = 0;
        int space = exp.indexOf(‘ ‘);//ÓÃÓÚËÑË÷¿Õ¸ñλÖÃ
        String s1 = exp.substring(0, space);//s1ÓÃÓÚ±£´æµÚÒ»¸öÔËËãÊý
        String op = exp.substring(space + 1, space + 2);//opÓÃÓÚ±£´æÔËËã·û
        String s2 = exp.substring(space + 3);//s2ÓÃÓÚ±£´æµÚ¶þ¸öÔËËãÊý
        double arg1 = Double.parseDouble(s1);//½«ÔËËãÊý´Óstringת»»ÎªSingle
        double arg2 = Double.parseDouble(s2);
        if(op.equals("£«")){
             r = arg1 + arg2;
        }else if(op.equals("£­")){
            r = arg1 - arg2;
        }else if(op.equals("¡Á")){
             r = arg1 * arg2;
        }else if(op.equals("¡Â")){
             if (arg2 == 0)
             {
                r=0;
             }
             else
             {
                 r = arg1 / arg2;
             }
        }       
        if(!s1.contains(".")&&!s2.contains(".")){
            int result = (int)r;
            et_showview.setText(result+"");
        }else{
            et_showview.setText(r+"");
        }
    }
//
//    /***
//     * @param exp
//     *            ËãÊý±í´ïʽ
//     * @return ¸ù¾Ý±í´ïʽ·µ»Ø½á¹û
//     */
//    private String getRs(String exp) {
//        Interpreter bsh = new Interpreter();
//        Number result = null;
//        try {
//            exp = filterExp(exp);
//            result = (Number) bsh.eval(exp);
//        } catch (EvalError e) {
//            e.printStackTrace();
//            return "0";
//        }
//        return result.doubleValue() + "";
//    }
//
//    /**
//     * @param exp
//     *            ËãÊý±í´ïʽ
//     * @return ÒòΪ¼ÆËã¹ý³ÌÖÐ,È«³ÌÐèÒªÓÐСÊý²ÎÓë.
//     */
//    private String filterExp(String exp) {
//        String num[] = exp.split("");
//        String temp = null;
//        double dtemp = 0 ;
//        String str_temp="";
//        for (int i = 0; i < num.length; i++) {
//            temp = num[i];
//            
//            if (temp.equals("+") || temp.equals("-") || temp.equals("¡Á")
//                    || temp.equals("¡Â")) {
//                if(dtemp==0){
//                dtemp=Double.parseDouble(str_temp);
//                }
//                
//                str_temp="";
//            }else{
//                str_temp=str_temp+temp;
//            }
//        }
//
//        int begin = 0, end = 0;
//        for (int i = 1; i < num.length; i++) {
//            temp = num[i];
//            if (temp.matches("[+-/()*]")) {
//                if (temp.equals("."))
//                    continue;
//                end = i - 1;
//                temp = exp.substring(begin, end);
//                if (temp.trim().length() > 0 && temp.indexOf(".") < 0)
//                    num[i - 1] = num[i - 1] + ".0";
//                begin = end + 1;
//            }
//        }
//        return Arrays.toString(num).replaceAll("[\\[\\], ]", "");
//    }
}

 

 

package com.imooc.calculator;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class ExpressionUtil {
    public double eval(String exp) {
        List<String> list = infixExpToPostExp(exp+"#");
        return doEval(list);
    }

    private double doEval(List<String> list) {
        Stack<String> stack = new Stack<String>();
        String element;
        double n1, n2, result;
        try {
            for (int i = 0; i < list.size(); i++) {
                element = list.get(i);
                if (isOperator(element)) {
                    n1 = Double.parseDouble(stack.pop());
                    n2 = Double.parseDouble(stack.pop());
                    result = doOperate(n2, n1, element);
                    stack.push(new Double(result).toString());
                } else {
                    stack.push(element);
                }
            }
            return Double.parseDouble(stack.pop());
        } catch (RuntimeException e) {
            throw new IllegalExpressionException(e.getMessage());
        }
    }
    private double doOperate(double n1, double n2, String operator) {
        if (operator.equals("+"))
            return n1 + n2;
        else if (operator.equals("-"))
            return n1 - n2;
        else if (operator.equals("*"))
            return n1 * n2;
        else
            return n1 / n2;
    }

    private boolean isOperator(String str) {
        return str.equals("+") || str.equals("-") || str.equals("*")
                || str.equals("/");
    }

    private List<String> infixExpToPostExp(String exp) {
        List<String> postExp = new ArrayList<String>();
        StringBuffer numBuffer = new StringBuffer();
        Stack<Character> opStack = new Stack<Character>();
        char ch, preChar;
        opStack.push(‘#‘);
        try {
            for (int i = 0; i < exp.length();) {
                ch = exp.charAt(i);
                switch (ch) {
                case ‘+‘:
                case ‘-‘:
                    if(i-1<0){
                        numBuffer.append(ch);
                        ch = exp.charAt(++i);
                        break;
                    }else{
                        char c = exp.charAt(i-1);
                        if(!Character.isDigit(c)){
                            numBuffer.append(ch);
                            ch = exp.charAt(++i);
                            break;
                        }
                    }
                case ‘*‘:
                case ‘/‘:
                    preChar = opStack.peek();
                    while (priority(preChar) >= priority(ch)) {
                        postExp.add("" + preChar);
                        opStack.pop();
                        preChar = opStack.peek();
                    }
                    opStack.push(ch);
                    i++;
                    break;
                case ‘(‘:
                    opStack.push(ch);
                    i++;
                    break;
                case ‘)‘:
                    char c = opStack.pop();
                    while (c != ‘(‘) {
                        postExp.add("" + c);
                        c = opStack.pop(); 
                    }
                    i++;
                    break;
                case ‘#‘:
                    char c1;
                    while (!opStack.isEmpty()) {
                        c1 = opStack.pop();
                        if (c1 != ‘#‘)
                            postExp.add("" + c1);
                    }
                    i++;
                    break;
                case ‘ ‘:
                case ‘\t‘:
                    i++;
                    break;
                default:
                    if (‘.‘==ch || Character.isDigit(ch)) {
                        while (Character.isDigit(ch)) {
                            numBuffer.append(ch);
                            ch = exp.charAt(++i);
                        }
                        if(‘.‘==ch){
                            numBuffer.append(‘.‘);
                            ch = exp.charAt(++i);
                        }else{
                            postExp.add(numBuffer.toString());
                            numBuffer = new StringBuffer();
                        }
                    } else {
                        throw new IllegalExpressionException("illegal operator");
                    }
                }
            }
        } catch (RuntimeException e) {
            throw new IllegalExpressionException(e.getMessage());
        }
        return postExp;
    }

    private int priority(char op) {
        switch (op) {
        case ‘+‘:
        case ‘-‘:
            return 1;
        case ‘*‘:
        case ‘/‘:
            return 2;
        case ‘(‘:
        case ‘#‘:
            return 0;
        }
        throw new IllegalExpressionException("Illegal operator");
    }

    public static void main(String[] args) {
        System.out.println("AB+AB-BC+ABC*DAB+AB".replaceAll("\\bAB\\b", "1"));
        ExpressionUtil eval = new ExpressionUtil();
        double result = eval.eval("0/3#");
        System.out.println(result);
    }

    class IllegalExpressionException extends RuntimeException {
        private static final long serialVersionUID = 1L;
        public IllegalExpressionException() {

        }
        public IllegalExpressionException(String info) {
            super(info);
        }
    }
}

 

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="60dip"
        android:background="@drawable/whitebg"
        android:editable="false"
        android:id="@+id/et_showview"
        android:gravity="bottom|right"
        android:textSize="20sp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="20dip"
        android:gravity="center_horizontal"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                android:id="@+id/btn_clear"
                android:background="@drawable/white_btn_selector"
                android:text="C" />

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                android:id="@+id/btn_del"
                android:background="@drawable/white_btn_selector"
                android:text="DEL" />

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                android:id="@+id/btn_divide"
                android:background="@drawable/white_btn_selector"
                android:text="÷" />

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                 android:id="@+id/btn_multiply"
                android:background="@drawable/white_btn_selector"
                android:text="×" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                 android:id="@+id/btn_7"
                android:background="@drawable/white_btn_selector"
                android:text="7" />

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                 android:id="@+id/btn_8"
                android:background="@drawable/white_btn_selector"
                android:text="8" />

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                android:id="@+id/btn_9"
                android:background="@drawable/white_btn_selector"
                android:text="9" />

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                android:id="@+id/btn_minus"
                android:background="@drawable/white_btn_selector"
                android:text="-" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                android:id="@+id/btn_4"
                android:background="@drawable/white_btn_selector"
                android:text="4" />

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                android:id="@+id/btn_5"
                android:background="@drawable/white_btn_selector"
                android:text="5" />

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                 android:id="@+id/btn_6"
                android:background="@drawable/white_btn_selector"
                android:text="6" />

            <Button
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                android:id="@+id/btn_pluse"
                android:background="@drawable/white_btn_selector"
                android:text="+" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" >

                    <Button
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:gravity="bottom|right"
                        android:paddingBottom="10dp"
                        android:paddingRight="10dp"
                        android:textSize="20sp"
                        android:id="@+id/btn_1"
                        android:background="@drawable/white_btn_selector"
                        android:text="1" />

                    <Button
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:layout_marginLeft="10dip"
                        android:gravity="bottom|right"
                        android:paddingBottom="10dp"
                        android:paddingRight="10dp"
                        android:textSize="20sp"
                        android:id="@+id/btn_2"
                        android:background="@drawable/white_btn_selector"
                        android:text="2" />

                    <Button
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:layout_marginLeft="10dip"
                        android:gravity="bottom|right"
                        android:paddingBottom="10dp"
                        android:paddingRight="10dp"
                        android:textSize="20sp"
                        android:id="@+id/btn_3"
                        android:background="@drawable/white_btn_selector"
                        android:text="3" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:orientation="horizontal" >

                    <Button
                        android:layout_width="130dp"
                        android:layout_height="60dp"
                        android:gravity="bottom|right"
                        android:paddingBottom="10dp"
                        android:paddingRight="10dp"
                        android:textSize="20sp"
                        android:id="@+id/btn_0"
                        android:background="@drawable/white_btn_selector"
                        android:text="0" />

                    <Button
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:layout_marginLeft="10dip"
                        android:gravity="bottom|right"
                        android:paddingBottom="10dp"
                        android:paddingRight="10dp"
                        android:text="." 
                        android:id="@+id/btn_point"
                        android:background="@drawable/white_btn_selector"
                        android:textSize="20sp"/>
                </LinearLayout>
            </LinearLayout>

            <Button
                android:layout_width="60dip"
                android:layout_height="130dip"
                android:layout_marginLeft="10dip"
                android:gravity="bottom|right"
                android:paddingBottom="10dp"
                android:paddingRight="10dp"
                android:textSize="20sp"
                android:id="@+id/btn_equal"
                android:background="@drawable/orange_btn_selector"
                android:text="=" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

 

一个很简陋的计算器

标签:

原文地址:http://www.cnblogs.com/sansansan/p/5139859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!