android开发实现的计算器

1 实验环境

实验环境:android studio

2.运行截图

计算器布局
计算机实现图片

3 源代码

3.1xml布局

<?xml version="1.0" encoding="UTF-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/resultText"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical|end"
        android:text="0"
        android:textSize="50sp" />

    -

    <GridLayout
        android:id="@+id/tableLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:columnCount="5"
        android:rowCount="5">

        <Button
            android:id="@+id/operator_delete"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="退格"
            android:textSize="26sp" />

        <Button
            android:id="@+id/operator_minus"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="+/-"
            android:textSize="40sp" />
        <Button
            android:id="@+id/operator_grade"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="1/X"
            android:textSize="30sp" />
        <Button
            android:id="@+id/operator_clear"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnSpan="2"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="清零"
            android:textSize="26sp" />

        <Button
            android:id="@+id/number_seven"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="7"
            android:textSize="40sp" />

        <Button
            android:id="@+id/number_eight"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="8"
            android:textSize="40sp" />

        <Button
            android:id="@+id/number_nine"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="9"
            android:textSize="40sp" />

        <Button
            android:id="@+id/operator_divide"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="/"
            android:textSize="40sp" />
        <Button
            android:id="@+id/operator_reminder"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="%"
            android:textSize="40sp" />

        <Button
            android:id="@+id/number_four"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="4"
            android:textSize="40sp" />

        <Button
            android:id="@+id/number_five"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="5"
            android:textSize="40sp" />

        <Button
            android:id="@+id/number_six"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="6"
            android:textSize="40sp" />


        <Button
            android:id="@+id/operator_ride"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="*"
            android:textSize="40sp" />

        <Button
            android:id="@+id/operator_signOfevolution"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="√"
            android:textSize="40sp" />


        <Button
            android:id="@+id/number_one"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="1"
            android:textSize="40sp" />

        <Button
            android:id="@+id/number_two"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="2"
            android:textSize="40sp" />

        <Button
            android:id="@+id/number_three"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="3"
            android:textSize="40sp" />

        <Button
            android:id="@+id/operator_subtract"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="—"
            android:textSize="40sp" />

        <Button
            android:id="@+id/operator_equalTo"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_rowSpan="2"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="="
            android:textSize="40sp" />

        <Button
            android:id="@+id/number_zero"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnSpan="2"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="0"
            android:textSize="40sp" />

        <Button
            android:id="@+id/operator_dot"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="."
            android:textSize="40sp" />

        <Button
            android:id="@+id/operator_add"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:text="+"
            android:textSize="40sp" />





    </GridLayout>

</LinearLayout>

2.activity


```java
package com.example.webb.testone;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.EventLogTags;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.JexlExpression;

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

public class counter extends AppCompatActivity {
    private TextView resultText; //文本域

    //private static final String TAG = "counter";
    private int index_number=0;//list列表下标
    private List<String> equation=new ArrayList<String>();//存储分解后的字符串
    private String str_figure="";//存储当前输入的计算数 或者 操作


    private Button number_zero;// 定义数字和点按钮
    private Button number_one;
    private Button number_two;
    private Button number_three;
    private Button number_four;
    private Button number_five;
    private Button number_six;
    private Button number_seven;
    private Button number_eight;
    private Button number_nine;
    private Button operator_dot;//点
    //定义数字按钮数组 共同添加监听器
    private Button[]buttons_number=new Button[]{number_zero,number_one,number_two,number_three,number_four,
            number_five,number_six,number_seven,number_eight,number_nine,operator_dot};
    private Integer id_number[]={R.id.number_zero,R.id.number_one,R.id.number_two,R.id.number_three, R.id.number_four,
            R.id.number_five,R.id.number_six,R.id.number_seven,R.id.number_eight,R.id.number_nine,R.id.operator_dot};
    private final String strs_number[]={"0","1","2","3","4","5","6","7","8","9","."};


    private Button operator_add;// 定义一般操作符
    private Button operator_subtract;
    private Button operator_ride;
    private Button operator_divide;
    private Button operator_reminder;//取余
    private Button operator_signOfevolution;//根号
    private Button operator_minus;//负号
    //定义一般操作符 共同添加监听器
    private Button []buttons_operator=new Button[]{operator_add,operator_subtract, operator_ride,
            operator_divide,operator_reminder,operator_signOfevolution,operator_minus};
    private Integer id_operator[]={R.id.operator_add, R.id.operator_subtract,R.id.operator_ride,
            R.id.operator_divide, R.id.operator_reminder,R.id.operator_signOfevolution,R.id.operator_minus};
   private  final String strs_operator[]={"+","-","*","/","%","√","-"};

    private Button operator_equalTo;//定义进行数据操作的操作符
    private Button operator_clear;
    private Button operator_delete;
    private Button operator_grade;//1/X
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counter);
        resultText = (TextView) findViewById(R.id.resultText);
        init_buttons_number();//初始化数字按钮
        init_buttons_operator();//初始化一般操作按钮
        into_special_operatorButton();//初始化特殊按钮
    }
    public void init_buttons_number() {
        for (int i = 0; i < buttons_number.length; i++)//初始化数字按钮
        {
           final int flag = i;//设置监听器
            buttons_number[i] = (Button) findViewById(id_number[i]);
            buttons_number[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String str = resultText.getText().toString();
                   // str_figure=split_String(str);//先获取进入链表的操作数
                    if ("0".equals(str))
                    {
                        if(strs_number[flag].equals("."))//点击为操作符.时
                        {
                            resultText.append(strs_number[flag]);
                        }
                        else  resultText.setText(strs_number[flag]);
                    }
                    else if (str_figure.length()!=0){
                        if (str_figure.contains(".") && strs_number[flag].equals("."))//当一个数中出现两个..{
                            Toast.makeText(counter.this, R.string.error_dot, Toast.LENGTH_SHORT).show();
                        }
                        else resultText.append(strs_number[flag]);
                    }
                    else resultText.append(strs_number[flag]);
                    str = resultText.getText().toString();
                    str_figure=split_String(str);//将当前输入的数进入操作数中
                }
            });
        }
    }
    public void init_buttons_operator() {
        for (int i=0;i<buttons_operator.length;i++){
            final int flag = i;
            buttons_operator[i]=(Button)findViewById(id_operator[i]);
            buttons_operator[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String str=resultText.getText().toString();
                    if(str_figure.length()!=0){
                        equation.add(str_figure);
                        str_figure="";
                        index_number++;
                    }
                    //当输入第一个操作符为- √ 可以输入 其它报错
                    if("0".equals(str)&&(strs_operator[flag].equals("-")||strs_operator[flag].equals("√")))
                    {
                        resultText.setText(strs_operator[flag]);
                        equation.add(strs_operator[flag]);
                        index_number++;
                    }
                    else if("0".equals(str)&&!strs_operator[flag].equals("-")&&!strs_operator[flag].equals("√"))
                    {
                       Toast.makeText(counter.this,R.string.error_operator,Toast.LENGTH_SHORT).show();
                    }
                    else {
                        //当连续输入不合法操作符时报错
                        if (strs_operator[flag].equals("-")&&(equation.size()>=2)&&!equation.get(index_number-2).equals("+")
                                &&!equation.get(index_number-2).equals("-")&& !equation.get(index_number-2).equals("*")
                                &&!equation.get(index_number-2).equals("/"))
                        {
                            resultText.append(strs_operator[flag]);
                            equation.add(strs_operator[flag]);
                            index_number++;
                        }
                        else if(!equation.get(index_number-1).equals("+")&&!equation.get(index_number-1).equals("-")&&
                        !equation.get(index_number-1).equals("*")&&!equation.get(index_number-1).equals("/")
                                &&!equation.get(index_number-1).equals("%"))
                        {
                            resultText.append(strs_operator[flag]);
                            equation.add(strs_operator[flag]);
                            index_number++;
                        }
                        else  Toast.makeText(counter.this,R.string.error_operator,Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

    }
    public void into_special_operatorButton(){
        operator_clear=findViewById(R.id.operator_clear);
        operator_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index_number=0;
                equation.clear();
                str_figure="";
                resultText.setText("0");

            }
        });
        operator_delete=findViewById(R.id.operator_delete);
        operator_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = resultText.getText().toString();
                if (str.length()==1){
                    resultText.setText("0");
                    index_number=0;
                    equation.clear();
                    str_figure="";
                }
                else if(str.substring(str.length()-1).equals("+")||str.substring(str.length()-1).equals("-")|| str.substring(str.length()-1).equals("*")
                        ||str.substring(str.length()-1).equals("/")||str.substring(str.length()-1).equals("%")||str.substring(str.length()-1).equals("√")) {
                    index_number--;
                    equation.remove(index_number);
                    resultText.setText(str.substring(0,str.length()-1));
                }
                else {
                    str_figure=str_figure.substring(0,str_figure.length()-1);
                    resultText.setText(str.substring(0,str.length()-1));
                }
            }
        });
        operator_equalTo=findViewById(R.id.operator_equalTo);
        operator_equalTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//判断最后一位是否为数字
                if(str_figure.length()!=0){
                    equation.add(str_figure);
                    str_figure="";
                    index_number++;
                }
               if(!equation.get(index_number-1).equals("+")&&!equation.get(index_number-1).equals("-")&&
                        !equation.get(index_number-1).equals("*")&&!equation.get(index_number-1).equals("/")
                        &&!equation.get(index_number-1).equals("%")&&!equation.get(index_number-1).equals("√"))
                {
                    resultText.setText(calculate());
               }
                else Toast.makeText(counter.this,R.string.error_operator,Toast.LENGTH_SHORT).show();
            }
        });
        operator_grade=findViewById(R.id.operator_grade);
        operator_grade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(str_figure.length()!=0){//将缓冲字符串入栈
                    equation.add(str_figure);
                    str_figure="";
                    index_number++;
                }
               double x=1.0/Double.valueOf(calculate());
               resultText.setText(String.valueOf(x));
            }
        });
    }
    public String split_String(String str){//拆分出当前需要存储的纯 操作数
        char[] str_char=str.toCharArray();
        String result_String="";//需要返回的字符串
        for(int i=str_char.length-1;i>=0;i--){
            if('+'!=str_char[i]&&'-'!=str_char[i]&&'*'!=str_char[i]&&'/'!=str_char[i]&&'%'!=str_char[i]
                    &&'√'!=str_char[i]){
                 result_String=str_char[i]+result_String;
            }
            else break;
        }
        return result_String;
    }
    public String calculate(){
        /*resultText.setText("");
        String aa="XY";
        for (int i=0;i<equation.size();i++){
            aa=aa+equation.get(i)+"xy";
        }
        index_number = 0;
        equation.clear();
        return aa;*/
   for (int i=0;i<equation.size();i++) {//简化list列表中的数据和操作数
       if (equation.get(i).equals("√")) {//出现连续多次根号情况
           int time = 0;
           for (int j = i; j < equation.size() && equation.get(j).equals("√"); j++, time++) ;
           if (equation.get(i+time).equals("-")) {
               index_number = 0;
               equation.clear();
               return "error";
           } else {
               double number1 = Double.valueOf(equation.get(i + time));
               if (!equation.get(i-1).equals("+")&&!equation.get(i-1).equals("-")&&!equation.get(i-1).equals("*")&&!equation.get(i-1).equals("/")
               &&!equation.get(i-1).equals("%")){
                  double number2=Double.valueOf(equation.get(i-1));
                   equation.set(i-1, String.valueOf(number2*Math.pow(number1, Math.pow(1 / 2.0, time))));
                   equation.remove(i);
                   for (int j = i ; j < i + time; j++) {
                       equation.remove(i);
                   }
                   i = 0;
                   continue;
               }
               equation.set(i, Math.pow(number1, Math.pow(1 / 2.0, time)) + "");
               for (int j = i + 1; j <= i + time; j++) {
                   equation.remove(i);
               }
               i = 0;
               continue;
           }
       }
   }
   for (int i=0;i<equation.size();i++) {//有负数的情况
       if(equation.get(i).equals("+")||equation.get(i).equals("-")||equation.get(i).equals("*")||equation.get(i).equals("/")||
               equation.get(i).equals("%")){
           if (equation.get(i+1).equals("-")){
             equation.set(i+1,equation.get(i+1)+equation.get(i+2));
             equation.remove((i+2));
             i=0;
             continue;
           }
           if (i==0){
               equation.set(i,equation.get(i)+equation.get(i+1));
               equation.remove((i+1));
               i=0;
               continue;
           }
       }
   }
   double number=0,numbera,numberb;
       for (int i=0;i<equation.size();i++)//先计算乘除取余运算
       {
           if(equation.size()==1){
               index_number=1;
               return equation.get(0);
           }
           if(equation.get(i).equals("*")||equation.get(i).equals("/")||equation.get(i).equals("%")){
                   numbera=Double.valueOf(equation.get(i-1));
                   numberb=Double.valueOf(equation.get(i+1));
            if (equation.get(i).equals("*")) {
                number = numbera * numberb;
            }
            else if (equation.get(i).equals("/")) {
                   number = numbera / numberb;
               }
               else if (equation.get(i).equals("%")) {
                   number = numbera % numberb;
               }
            equation.set(i-1,String.valueOf(number));
            equation.remove(i);
            equation.remove(i);
            i=0;
            continue;
           }
       }
        for (int i=0;i<equation.size();i++)//在计算加减法
        {
            if(equation.size()==1){
                index_number=1;
                return equation.get(0);
            }
            if(equation.get(i).equals("+")||equation.get(i).equals("-")){
                numbera=Double.valueOf(equation.get(i-1));
                numberb=Double.valueOf(equation.get(i+1));
                if (equation.get(i).equals("+")) {
                    number = numbera + numberb;
                }
                else if (equation.get(i).equals("-")) {
                    number = numbera-numberb;
                }
                equation.set(i-1,String.valueOf(number));
                equation.remove(i);
                equation.remove(i);
                i=0;
                continue;
            }
        }
        return equation.get(0);
    }
    /*public  Object calculate(String str){//字符串表达式计算结果
       JexlEngine jexlEngine = new JexlBuilder().create();
        JexlExpression jexlExpression = jexlEngine.createExpression(str);
        Object evaluate = jexlExpression.evaluate(null);
        return evaluate;
    }*/
}






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值