关闭

自学安卓的第一个小小小App——计算器,希望前辈们多多指点

标签: android计算器
89人阅读 评论(0) 收藏 举报
分类:

安卓自学中,基础知识基本都撸过了一遍,于是打算从最简单的开始实践,于是计算器这个冤大头就惨遭了我的毒手。
在反复调BUG后终于勉强可以叫他是个计算器了,虽然有些乱,但心里还是挺欢喜的。
对于一个初学者,我觉得代码一定写的不堪入目,不拿出去,更不能自己的代码有多丑,所以专门来po一po,希望大神给出更多良好的建议。
PS:正则部分是参考的网上资源,并非原创。

这里写代码片

这里写代码片`
package android.yang.calculator;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText cal;
    private Button num0;
    private Button num1;
    private Button num2;
    private Button num3;
    private Button num4;
    private Button num5;
    private Button num6;
    private Button num7;
    private Button num8;
    private Button num9;
    private Button add;
    private Button sub;
    private Button mul;
    private Button div;
    private Button point;
    private Button remove;
    private Button clear;
    private Button equ;

    private StringBuilder sb = new StringBuilder();
    Editable editable = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        setContentView(R.layout.activity_main);

        //初始化变量
        cal = (EditText) findViewById(R.id.cal);
        num0 = (Button) findViewById(R.id.num0);
        num1 = (Button) findViewById(R.id.num1);
        num2 = (Button) findViewById(R.id.num2);
        num3 = (Button) findViewById(R.id.num3);
        num4 = (Button) findViewById(R.id.num4);
        num5 = (Button) findViewById(R.id.num5);
        num6 = (Button) findViewById(R.id.num6);
        num7 = (Button) findViewById(R.id.num7);
        num8 = (Button) findViewById(R.id.num8);
        num9 = (Button) findViewById(R.id.num9);
        add = (Button) findViewById(R.id.add);
        sub = (Button) findViewById(R.id.sub);
        mul = (Button) findViewById(R.id.mul);
        div = (Button) findViewById(R.id.div);
        point = (Button) findViewById(R.id.point);
        remove = (Button) findViewById(R.id.remove);
        clear = (Button) findViewById(R.id.clear);
        equ = (Button) findViewById(R.id.equ);


        //按钮的点击事件
        num0.setOnClickListener(this);
        num1.setOnClickListener(this);
        num2.setOnClickListener(this);
        num3.setOnClickListener(this);
        num4.setOnClickListener(this);
        num5.setOnClickListener(this);
        num6.setOnClickListener(this);
        num7.setOnClickListener(this);
        num8.setOnClickListener(this);
        num9.setOnClickListener(this);
        add.setOnClickListener(this);
        sub.setOnClickListener(this);
        mul.setOnClickListener(this);
        div.setOnClickListener(this);
        point.setOnClickListener(this);
        remove.setOnClickListener(this);
        clear.setOnClickListener(this);
        equ.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        String ex = "";
        switch (view.getId()){
            case R.id.num0:
                ex = "0";
                sb.append(ex);
             //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.num1:
                ex = "1";
                sb.append(ex);
            //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.num2:
                ex = "2";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.num3:
                ex = "3";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.num4:
                ex = "4";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.num5:
                ex = "5";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.num6:
                ex = "6";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.num7:
                ex = "7";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.num8:
                ex = "8";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.num9:
                ex = "9";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.add:
                ex = "+";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.sub:
                ex = "-";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.mul:
                ex = "x";
                String ex2 = "*";
                sb.append(ex2);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.div:
                ex = "÷";
                String ex3 = "/";
                sb.append(ex3);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.point:
                ex = ".";
                sb.append(ex);
                //   calView(sb);
                calView(sb,ex);
                break;
            case R.id.remove:
                calRemove();
                break;
            case R.id.clear:
                clearView();
                break;
            case R.id.equ:
                //点击等号后,计算字符串的结果
                ReportUtil result = new ReportUtil();
                double re = result.result(sb);
                //检验是否合乎输入要求
                if(re == Double.MAX_VALUE){
                    String tips = "算式格式错误";
                    sb.append(tips);
                    cal.setText(sb);
                    cal.setSelection(sb.length());
                }else{
                    String strNext = Double.toString(re);
                    cal.setText(strNext);
                    cal.setSelection(strNext.length());
                    next(re);
                }
                break;
        }
    }

    //编辑框来显示数据
    private void calView(StringBuilder sb,String ex){
      /*  cal.setText(sb);
        cal.setSelection(sb.length());*/
        int index = cal.getSelectionStart();
        editable = cal.getText();
        editable.insert(index,ex);

    }

    //退格键的功能实现
    private void calRemove(){
        if(cal.getSelectionStart() != 0 && cal.getText().toString().length() != 0) {
            /*String str = cal.getText().toString();
            String newStr = str.substring(0, str.length() - 1);
            cal.setText(newStr);
            cal.setSelection(newStr.length());*/

            String str = cal.getText().toString();
            String newStr = str.substring(0, str.length() - 1);
            sb = new StringBuilder(newStr);
            int index = cal.getSelectionStart();
            editable = cal.getText();
            editable.delete(index-1,index);
        }
    }

    //删除键的功能实现
    private void clearView(){
        String str = "";
        cal.setText(str);
        StringBuilder sb3 = new StringBuilder();
        sb = sb3;
    }

    //点击等号后重新设置sb,
    private void next(double re){
        StringBuilder sb2 = new StringBuilder();
        sb = sb2;
        sb.append(Double.toString(re));
    }

}


package android.yang.calculator;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 报表工具类
 * @author ZYWANG 2009-7-28
 */
public final class ReportUtil {



    //定义字符数组检验输入是否正确
    static String[] strss = {"++","+-","+*","+/",
            "--","-+","-*","-/",
            "*+","*-","**","*/",
            "/+","/-","//","/*",};
    static boolean ok = true;
    /**
     * 格式化日期
     * @param obj 日期对象
     * @param format 格式化字符串
     * @return
     * @author ZYWANG 2009-8-26
     */
    public static String formatDate(Object obj, String format) {
        if (obj == null)
            return "";

        String s = String.valueOf(obj);
        if (format == null || "".equals(format.trim())) {
            format = "yyyy-MM-dd";
        }
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            s = dateFormat.format(obj);
        } catch (Exception e) {
        }
        return s;
    }

    /**
     * 格式化数字
     * @param obj 数字对象
     * @param format 格式化字符串
     * @return
     * @author ZYWANG 2009-8-26
     */
    public static String formatNumber(Object obj, String format) {
        if (obj == null)
            return "";

        String s = String.valueOf(obj);
        if (format == null || "".equals(format.trim())) {
            format = "#.00";
        }
        try {
            if (obj instanceof Double || obj instanceof Float) {
                if (format.contains("%")) {
                    NumberFormat numberFormat = NumberFormat.getPercentInstance();
                    s = numberFormat.format(obj);
                } else {
                    DecimalFormat decimalFormat = new DecimalFormat(format);
                    s = decimalFormat.format(obj);
                }
            } else {
                NumberFormat numberFormat = NumberFormat.getInstance();
                s = numberFormat.format(obj);
            }
        } catch (Exception e) {
        }
        return s;
    }

    /**
     * 计算字符串四则运算表达式
     * @param string
     * @return
     * @author ZYWANG 2009-8-31
     */
    public static String computeString(String string) {
        String regexCheck = "[\\(\\)\\d\\+\\-\\*/\\.]*";// 是否是合法的表达式

        if (!Pattern.matches(regexCheck, string))
            return string;

        Matcher matcher = null;
        String temp = "";
        int index = -1;
        String regex = "\\([\\d\\.\\+\\-\\*/]+\\)";// 提取括号表达式
        string = string.replaceAll("\\s", "");// 去除空格
        try {
            Pattern pattern = Pattern.compile(regex);
            // 循环计算所有括号里的表达式
            while (pattern.matcher(string).find()) {
                matcher = pattern.matcher(string);
                while (matcher.find()) {
                    temp = matcher.group();
                    index = string.indexOf(temp);
                    string = string.substring(0, index)
                            + computeStirngNoBracket(temp)
                            + string.substring(index + temp.length());
                }
            }
            // 最后计算总的表达式结果
            string = computeStirngNoBracket(string);
        } catch (NumberFormatException e) {
            return e.getMessage();
        }
        return string;
    }

    /**
     * 计算不包含括号的表达式
     * @param string
     * @return
     * @author ZYWANG 2009-8-31
     */
    private static String computeStirngNoBracket(String string) {
        string = string.replaceAll("(^\\()|(\\)$)", "");
        String regexMultiAndDivision = "[\\d\\.]+(\\*|\\/)[\\d\\.]+";
        String regexAdditionAndSubtraction = "(^\\-)?[\\d\\.]+(\\+|\\-)[\\d\\.]+";

        String temp = "";
        int index = -1;

        // 解析乘除法
        Pattern pattern = Pattern.compile(regexMultiAndDivision);
        Matcher matcher = null;
        while (pattern.matcher(string).find()) {
            matcher = pattern.matcher(string);
            if (matcher.find()) {
                temp = matcher.group();
                index = string.indexOf(temp);
                string = string.substring(0, index) + doMultiAndDivision(temp)
                        + string.substring(index + temp.length());
            }
        }

        // 解析加减法
        pattern = Pattern.compile(regexAdditionAndSubtraction);
        while (pattern.matcher(string).find()) {
            matcher = pattern.matcher(string);
            if (matcher.find()) {
                temp = matcher.group();
                index = string.indexOf(temp);
                if (temp.startsWith("-")) {
                    string = string.substring(0, index)
                            + doNegativeOperation(temp)
                            + string.substring(index + temp.length());
                } else {
                    string = string.substring(0, index)
                            + doAdditionAndSubtraction(temp)
                            + string.substring(index + temp.length());
                }
            }
        }

        return string;
    }

    /**
     * 执行乘除法
     * @param string
     * @return
     * @author ZYWANG 2009-8-31
     */
    private static String doMultiAndDivision(String string) {
        String value = "";
        double d1 = 0;
        double d2 = 0;
        String[] temp = null;
        if (string.contains("*")) {
            temp = string.split("\\*");
        } else {
            temp = string.split("/");
        }

        if (temp.length < 2)
            return string;

        d1 = Double.valueOf(temp[0]);
        d2 = Double.valueOf(temp[1]);
        if (string.contains("*")) {
            value = String.valueOf(d1 * d2);
        } else {
            value = String.valueOf(d1 / d2);
        }

        return value;
    }

    /**
     * 执行加减法
     * @param string
     * @return
     * @author ZYWANG 2009-8-31
     */
    private static String doAdditionAndSubtraction(String string) {
        double d1 = 0;
        double d2 = 0;
        String[] temp = null;
        String value = "";
        if (string.contains("+")) {
            temp = string.split("\\+");
        } else {
            temp = string.split("\\-");
        }

        if (temp.length < 2)
            return string;

        d1 = Double.valueOf(temp[0]);
        d2 = Double.valueOf(temp[1]);
        if (string.contains("+")) {
            value = String.valueOf(d1 + d2);
        } else {
            value = String.valueOf(d1 - d2);
        }

        return value;
    }

    /**
     * 执行负数运算
     * @param string
     * @return
     * @author ZYWANG 2010-11-8
     */
    private static String doNegativeOperation(String string) {
        String temp = string.substring(1);
        if (temp.contains("+")) {
            temp = temp.replace("+", "-");
        } else {
            temp = temp.replace("-", "+");
        }
        temp = doAdditionAndSubtraction(temp);
        if (temp.startsWith("-")) {
            temp = temp.substring(1);
        } else {
            temp = "-" + temp;
        }
        return temp;
    }

    public static double result(StringBuilder sb) {
        String s = sb.toString();
        ok = true;
        for (String contain:strss
             ) {
            if(s.contains(contain)){
                ok = false;
                return Double.MAX_VALUE;
            }
        }

        if (ok) {
            s = computeString(s);
        }
        return Double.parseDouble(s);
    }
}

这里写代码片
“`

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:94次
    • 积分:11
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档