您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

基于Android简易四则计算器设计实现

Android计算器设计实现

  1. 使用线性布局进行页面设计
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <LinearLayout
        android:id="@+id/l1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"></LinearLayout>

    <LinearLayout
        android:id="@+id/l2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"></LinearLayout>

    <LinearLayout
        android:id="@+id/l3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"></LinearLayout>

    <LinearLayout
        android:id="@+id/l4"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"></LinearLayout>

    <LinearLayout
        android:id="@+id/l5"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"></LinearLayout>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="bottom|right"
        android:text="by 秀秀咻一"
        android:textSize="25sp"
        android:textStyle="italic"/>
</LinearLayout>
  1. 在activity的onCreate事件中使用循环动态生成按钮,为每个按钮添加监听器
package com.example.calculator;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Build;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {
    LinearLayout l1,l2,l3,l4,l5;
    TextView tv;
    StringBuilder str=new StringBuilder();
    String[] s1={"AC","D","(",")"};
    String[] s2={"7","8","9","+"};
    String[] s3={"4","5","6","-"};
    String[] s4={"1","2","3","*"};
    String[] s5={".","0","=","/"};
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        l1=findViewById(R.id.l1);
        l2=findViewById(R.id.l2);
        l3=findViewById(R.id.l3);
        l4=findViewById(R.id.l4);
        l5=findViewById(R.id.l5);
        tv=findViewById(R.id.textView);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,40);
        for(int i=0;i<4;i++){
            Button tempb=new Button(MainActivity.this);
            tempb.setId(View.generateViewId());
            tempb.setTag(s1[i]);
            tempb.setText(s1[i]);
            tempb.setTextSize(TypedValue.COMPLEX_UNIT_SP,48);
            tempb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String tmp=v.getTag().toString();
                    if(tmp.equals("AC")){
                        tv.setText("");
                        str.setLength(0);
                    }else if(tmp.equals("D")){
                        String tmps=tv.getText().toString();
                        tv.setText(tmps.substring(0,tmps.length()-1));
                        str.deleteCharAt(str.length()-1);
                    }else{
                        tv.setText(tv.getText()+tmp);
                        str.append(tmp);
                    }
                }
            });
            l1.addView(tempb);
        }
        for(int i=0;i<4;i++) {
            Button tempb = new Button(MainActivity.this);
            tempb.setId(View.generateViewId());
            tempb.setTag(s2[i]);
            tempb.setText(s2[i]);
            tempb.setTextSize(TypedValue.COMPLEX_UNIT_SP,48);
            tempb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String tmp=v.getTag().toString();
                    tv.setText(tv.getText()+tmp);
                    str.append(tmp);
                }
            });
            l2.addView(tempb);
        }
        for(int i=0;i<4;i++) {
            Button tempb = new Button(MainActivity.this);
            tempb.setId(View.generateViewId());
            tempb.setTag(s3[i]);
            tempb.setText(s3[i]);
            tempb.setTextSize(TypedValue.COMPLEX_UNIT_SP,48);
            tempb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String tmp=v.getTag().toString();
                    tv.setText(tv.getText()+tmp);
                    str.append(tmp);
                }
            });
            l3.addView(tempb);
        }
        for(int i=0;i<4;i++) {
            Button tempb = new Button(MainActivity.this);
            tempb.setId(View.generateViewId());
            tempb.setTag(s4[i]);
            tempb.setText(s4[i]);
            tempb.setTextSize(TypedValue.COMPLEX_UNIT_SP,48);
            tempb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String tmp=v.getTag().toString();
                    tv.setText(tv.getText()+tmp);
                    str.append(tmp);
                }
            });
            l4.addView(tempb);
        }
        for(int i=0;i<4;i++) {
            final Button tempb = new Button(MainActivity.this);
            tempb.setId(View.generateViewId());
            tempb.setTag(s5[i]);
            tempb.setText(s5[i]);
            tempb.setTextSize(TypedValue.COMPLEX_UNIT_SP,48);
            tempb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String tmp=v.getTag().toString();
                    tv.setText(tv.getText()+tmp);
                    if(!tmp.equals("=")){
                        str.append(tmp);
                    }
                    else{
                        SuffixExpression suffixExpression=new SuffixExpression();
                        List<String> list=suffixExpression.getListString(str.toString());
                        List<String> ls=suffixExpression.getPostfixExpression(list);
                        String sum=suffixExpression.get(ls);
                        tv.setText(tv.getText()+sum);
                        str.setLength(0);
                        str.append(sum);
                    }
                }
            });
            l5.addView(tempb);
        }
    }
}
  1. 简单工厂模式的调用
    (1)定义运算接口(抽象产品类)
package com.example.calculator;

public interface Calculation {
    public String result(double num1,double num2);
}

(2)具体产品类

package com.example.calculator;

public class addition implements Calculation {
    @Override
    public String result(double num1, double num2) {
        return String.valueOf(num1+num2);
    }
}

(3)简单工厂类

package com.example.calculator;

public class CalFactory {
    static  Calculation mycal;
    static  Calculation getMycal(String arg){
        switch (arg){
            case"+":
                mycal=new addition();
                break;
            case"-":
                mycal=new substraction();
                break;
            case"*":
                mycal=new multiplication();
                break;
            case"/":
                mycal=new division();
                break;
        }
        return mycal;
    }
}

(4)简单工厂调用

package com.example.calculator;

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

public class SuffixExpression {
    //对字符串进行分解,形成一个list(中缀表达式)
    public List<String> getListString(String s) {
        List<String> list = new ArrayList<String>();
        String str;
        char c;
        for (int i=0;i<s.length();i++){
            if((c=s.charAt(i))<48 || (c=s.charAt(i))>57){  //判断字符
                list.add(""+c);
            }else {
                str = "";
                int p = 0;
                while (i<s.length() && (((c=s.charAt(i))>=48 && (c=s.charAt(i))<=57)||(c=s.charAt(p))=='.')){  //是数字
                    str += c;
                    p = i+1;
                    if(p<s.length() && (((c=s.charAt(p))>=48 && (c=s.charAt(p))<=57)||(c=s.charAt(p))=='.')){
                        i++;
                    }else
                    {
                        break;
                    }
                }
                list.add(str);
                System.out.println(list);
            }
        }
        return list;
    }
    //将中缀表达式转换成后缀表达式
    public List<String> getPostfixExpression(List<String> ls) {
        Stack<String> s1 = new Stack<String>();  //运算符栈
        List<String> s2 = new ArrayList<String>();  //结果list
        for (String item : ls){  //遍历每个
            if(isNumeric(item)){  //如果是数字,直接加入s2
                s2.add(item);
            }else if(item.equals("(")){  //如果是( 直接压入s1
                s1.push(item);
            }else if(item.equals(")")){  //如果是 ) 进行判断
                while (!s1.peek().equals("(")){  //如果s1栈顶的不是( 就把s1栈顶的值弹出,并加入到s2中
                    s2.add(s1.pop());
                }
                s1.pop();  // 如果是s1栈顶是(就弹出,消除括号对
            }else {
                while (s1.size() != 0 && isPriority(item) <= isPriority(s1.peek())){  //如果当前符号的优先级 <= s1栈顶的优先级  就把s1栈顶的弹出,并加入到s2中
                    s2.add(s1.pop());
                }
                s1.push(item);  //如果s1栈中没有符号,就直接压入
            }
        }
        while (s1.size() !=  0){  //如果s1中有符号,就弹出,并加入s2中
            s2.add(s1.pop());
        }
        return  s2;
    }
    //判断运算符的优先级
    public int isPriority(String val){
        if(val.equals("*")  ||  val.equals("/")){
            return 1;
        }
        else if(val.equals("+")  ||  val.equals("-")){
            return 0;
        }else {
            return -1;
        }
    }
    //判断是否为数字
    public boolean isNumeric(String str){
        Pattern pattern=Pattern.compile("^(\\-|\\+)?\\d+(\\.\\d+)?$");
        return  pattern.matcher(str).matches();
    }
    //获取计算结果
    public String get(List<String> list){
        String result;
        Stack<String> stack = new Stack<String>();
        for (String item : list) {
            if (isNumeric(item)) {
                stack.push(item);
            } else {
                double num2=0,num1=0;
                if(!stack.empty()){
                    num2 = Double.parseDouble(stack.pop());
                }
                if(!stack.empty()){
                    num1 = Double.parseDouble(stack.pop());
                }
                //根据不同运算符进行不同运算
                Calculation myope = CalFactory.getMycal(item);
                    result = myope.result(num1, num2);
                    stack.push("" + result);
            }
        }
        result=stack.pop();
        return result;
    }
}

运行效果
运行效果


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进