中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何用Android開發實現簡單的計算器功能

發布時間:2022-04-16 16:42:04 來源:億速云 閱讀:173 作者:iii 欄目:開發技術

這篇“如何用Android開發實現簡單的計算器功能”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“如何用Android開發實現簡單的計算器功能”文章吧。

計算器項目,要求實現加、減、乘、除、求倒數、求平方根等簡單運算。

真機調試結果如下圖:

如何用Android開發實現簡單的計算器功能

布局文件:main_activity.xml

<?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:background="#FFFFFF"
    android:orientation="vertical"
    android:padding="3dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

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

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="簡單計算器"
                android:textColor="#000000"
                android:textSize="20sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#ffffff"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_result"
                    android:background="#4E4B4B"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="right|bottom"
                    android:lines="3"
                    android:maxLines="3"
                    android:scrollbars="vertical"
                    android:text="0"
                    android:textColor="#FFFFFF"
                    android:textSize="35sp" />
            </LinearLayout>

            <GridLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:columnCount="4"
                >

                <Button
                    android:id="@+id/btn_cancel"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:shadowColor="@color/purple_500"
                    android:text="CE"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_divide"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="÷"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_multiply"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="×"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_clear"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="C"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_seven"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="7"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_eight"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="8"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp" />

                <Button
                    android:id="@+id/btn_nine"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="9"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_plus"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="+"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_four"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="4"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_five"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="5"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_six"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="6"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_minus"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="-"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_one"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="1"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_two"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="2"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_three"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="3"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <ImageButton
                    android:id="@+id/ib_sqrt"
                    android:layout_width="90dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:scaleType="centerInside"
                    android:src="@drawable/sqrt"
                    android:gravity="center"
                    android:layout_marginStart="4dp"/>

                <Button
                    android:id="@+id/btn_reciprocal"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="1/x"
                    android:textColor="@color/black"
                    android:textSize="28sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_zero"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="0"
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_dot"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="."
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>

                <Button
                    android:id="@+id/btn_equal"
                    android:layout_width="85dp"
                    android:layout_height="70dp"
                    android:backgroundTint="@color/gray"
                    android:gravity="center"
                    android:text="="
                    android:textColor="@color/black"
                    android:textSize="30sp"
                    android:layout_marginStart="5dp"/>
            </GridLayout>

        </LinearLayout>
    </ScrollView>


</LinearLayout>

活動頁面:MainActivity.java

package com.example.calculator;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.calculator.cal.CoreAlgorithm;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

        private TextView tv_result; // 聲明一個文本視圖對象
        private double result =0; // 當前的計算結果
        private String showText = ""; // 顯示的文本內容
        private final StringBuilder builder=new StringBuilder();  //存儲運算式子的字符串構造器


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tv_result = findViewById(R.id.tv_result);

            int[] buttonSeq={
                    R.id.btn_cancel, // “取消”按鈕
                    R.id.btn_divide,// “除法”按鈕
                    R.id.btn_multiply , // “乘法”按鈕
                    R.id.btn_clear , // “清除”按鈕
                    R.id.btn_seven , // 數字7
                    R.id.btn_eight , // 數字8
                    R.id.btn_nine , // 數字9
                    R.id.btn_plus , // “加法”按鈕
                    R.id.btn_four , // 數字4
                    R.id.btn_five , // 數字5
                    R.id.btn_six , // 數字6
                    R.id.btn_minus , // “減法”按鈕
                    R.id.btn_one , // 數字1
                    R.id.btn_two , // 數字2
                    R.id.btn_three , // 數字3
                    R.id.btn_reciprocal , // 求倒數按鈕
                    R.id.btn_zero , // 數字0
                    R.id.btn_dot , // “小數點”按鈕
                    R.id.btn_equal , // “等號”按鈕
                    R.id.ib_sqrt // “開平方”按鈕
            };

            for(int buttonId:buttonSeq)
                findViewById(buttonId).setOnClickListener(this);

            builder.append(0);
        }

//符號分類
        //數字
        //四則運算符
        //小數點
        //根號,倒數,等號,直接出結果
        //CE C


        @Override
        public void onClick(View v) {
            int id=v.getId();
            String inputText="";

//        if(result!=0){          //如果結果不為0,則按照結果進行運算
//            clear();
//            builder.append(result);
//        }


            //若不為根號,因為根號按鈕無法取值
            if(id!=R.id.ib_sqrt) {
                inputText = ((TextView) v).getText().toString();

                //判斷是否為數字、小數點以及四則運算符

                if (inputText.matches("\\d|\\.")) {         //輸入是否為數字或點號
                    resultCheck();
                    if(builder.toString().equals("0")){
                        builder.deleteCharAt(builder.length()-1);}

                    builder.append(inputText);
                    if(verifyExp(builder.toString())){
                        refreshText(builder.toString());      //表達式正確刷新
                    }else{
                        builder.deleteCharAt(builder.length() - 1);  //表達式不正確刪除最后一位字符
                    }


                } else if (inputText.matches("\\+|-|×|÷")) {        //輸入為四則運算符

                    resultCheck();

                    builder.append(inputText);
                    if(verifyExp(builder.toString())){
                        refreshText(builder.toString());
                    }else{                                               //更替運算符操作
                        builder.deleteCharAt(builder.length() - 1);
                        builder.deleteCharAt(builder.length() - 1);
                        builder.append(inputText);
                        refreshText(builder.toString());
                    }

                }
                else {                          //點擊了CE C 1/X =

                    switch (inputText) {
                        case "CE":
                            resultCheck();
                            //有字符才能刪除
                            if (builder.length() > 0) {
                                builder.deleteCharAt(builder.length() - 1);
                                refreshText(builder.toString());
                            } else {

                                Toast.makeText(this, "沒有數字可刪了", Toast.LENGTH_SHORT).show();
                            }
                            break;
                        case "C":
                            refreshText("");
                            result=0.0;
                            builder.delete(0, builder.length());    //builder清空
                            builder.append(0);
                            break;
                        case "1/x":
                            resultCheck();
                            result=1/(CoreAlgorithm.calExp(builder.toString()));
                            refreshText("1/("+builder.toString()+")=\n"+result);
                            break;
                        case "=":
                            resultCheck();
                            if(result==0.0) {
                                result = CoreAlgorithm.calExp(builder.toString());
//                                builder.append("=");//容易出錯 ,按等號會把這個式子進行運算
                                refreshText(builder.toString() + "=\n" + result);
                            }
                            break;
                        default:
                            Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
                    }

                }
            }else{      // 點擊了開根號,由于算法不支持有運算符在前,目前已經支持
                resultCheck();  //經過一次檢查結果被清零,結果存于builder中
                 result = Math.sqrt(CoreAlgorithm.calExp(builder.toString()));
                 refreshText("√(" + builder.toString() + ")=\n" + result);

            }

        }

        //檢查整個表達式
        public boolean verifyExp(String exp){       //驗證整個表達式是否合法
            String lastNum="";
            String[] sp=exp.split("\\+|-|×|÷");      //將操作數分割出來
            char lastChar=exp.charAt(exp.length()-1);       //獲得最后一個字符

            lastNum=sp[sp.length-1];     //取得最后一位操作數

            if(String.valueOf(lastChar).matches("\\+|-|×|÷"))  //如果當前符號為四則運算符
            {
                lastNum="";
                return exp.matches(".*(\\d[+-×÷])|.*(\\.[+-×÷])");      //驗證最后的運算符是否符合只有一個原則

            }else{                                                          //最后一位為運算數
                return  lastNum.matches("^[-]?\\d*\\.?\\d*");   //驗證最后一位運算數是否合法

            }
        }


        // 刷新文本顯示
        private void refreshText(String text) {
            showText = text;
            tv_result.setText(showText);
        }

        // 清空并初始化
        private void clear() {
            builder.delete(0, builder.length());
            showText="";
        }

        //基本每個出結果的按鈕都要執行一次這個函數
        public void resultCheck(){      //運算結果檢查,有結果用結果,結果不為數字進行處理
            if(result!=0){          //如果結果不為0,則按照結果進行運算
                String res=String.valueOf(result);
                if(res.matches("^[-]?\\d*\\.?\\d*")){   //若為浮點數字
                    clear();
                    builder.append(result);
                    result=0;    //結果不清零,檢查的時候就會一直重復放入結果
                }else{      //若結果為字母,分母為0會返回Infinity,以及負數開方
                    clear();
                    builder.append("0");
                    result=0;
                }
            }

            if(builder.length()==0){
                builder.append(0);
            }

        }

}

核心算法:CoreAlgorithm.java

package com.example.calculator.cal;


import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CoreAlgorithm {

        private static final Stack<Double> st = new Stack<>();      //原始數字棧
        private static final Queue<Double> qu = new ArrayDeque<>();  //序列化數字隊列,
        private static final Queue<String> queOp = new ArrayDeque<>();        //符號隊列
        private static final Queue<String> newQueOp = new ArrayDeque<>();

        public static double calExp(String exp) {


//       String str="1+3*2-8/2+6";
//        String str="1+3*2/1";

            //本算法似乎不支持符號在前面,目前算法已經改進


            //處理運算符在式子最后
            if (exp.matches(".*[\\+\\-×÷]")) {
                exp = exp.substring(0, exp.length() - 1);
            }

            String[] sp; //存放分割數組

            //運算符在式子最前面
            if (exp.matches("[\\+\\-×÷].*")) {
                String fistElem=exp.substring(0,1); //截取首個字符
                exp=exp.substring(1);       //舍去首個字符
                //分割字符,提取數字
                sp = exp.split("\\+|-|×|÷");
                if(fistElem.equals("-")){       //首個字符為負號
                    sp[0]="-"+sp[0];        //添加負號
                }
            }else{  //沒有符號在前
                sp = exp.split("\\+|-|×|÷");
            }

            //之前直接分割字符會導致,數組第一位為空,導致程序無法運行

            for (int i = sp.length - 1; i >= 0; i--) {
                if (sp[i].equals(".")) {
                    st.push(0.0);       //替換點號
                } else {
                    st.push(Double.parseDouble(sp[i]));
                }

            }

            //尋找匹配字符串
            Pattern p = Pattern.compile("\\+|-|×|÷");
            Matcher m = p.matcher(exp);
            while (m.find()) {

                queOp.add(m.group());
            }

//        for(int i=sp.length-1;i>=0;i--){
//           System.out.println(st.pop());
//        }

//       int size=queNum.size();
//       for(int i=0;i<size;i++)
//           System.out.println(queNum.poll());

            //運算降級序列化
            while (st.size() > 0) {

                String currOp;

                if (queOp.size() > 0) {
                    currOp = queOp.poll();
                } else {
                    currOp = "0";
                }

                switch (currOp) {
                    case "×":
                        st.push(st.pop() * st.pop());
                        break;
                    case "÷":
                        st.push(st.pop() / st.pop());
                        break;
                    case "+":
                        qu.add(st.pop());
                        newQueOp.add("+");
                        break;
                    case "-":
                        qu.add(st.pop());
                        newQueOp.add("-");
                        break;
                    default:
                        qu.add(st.pop());

                }
            }

            //正常運算
            if (qu.size() > 0) {
                double res = qu.poll();
                while (qu.size() > 0) {

                    String op = "";
                    if (newQueOp.size() > 0) {
                        op = newQueOp.poll();
                    } else {
                        op = "none";
                    }

                    switch (op) {
                        case "+":
                            res += qu.poll();
                            break;
                        case "-":
                            res -= qu.poll();
                            break;
                        default:
                            System.out.println("none");
                    }

                }

                return res;

            }

            return 0.0;
        }
}

以上就是關于“如何用Android開發實現簡單的計算器功能”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

乃东县| 阜新市| 霞浦县| 将乐县| 太谷县| 宜宾市| 依安县| 福海县| 宜良县| 楚雄市| 天津市| 邵东县| 昂仁县| 武邑县| 阜新市| 长泰县| 炎陵县| 洞口县| 怀集县| 石首市| 城口县| 武胜县| 阆中市| 莒南县| 新邵县| 泰顺县| 无极县| 正蓝旗| 玉树县| 金堂县| 南乐县| 寻甸| 美姑县| 湖南省| 新民市| 铜川市| 丰县| 喜德县| 新源县| 进贤县| 凯里市|