GVKun编程网logo

Java怎么利用栈实现简易计算器功能(java怎么利用栈实现简易计算器功能)

17

本文将分享Java怎么利用栈实现简易计算器功能的详细内容,并且还将对java怎么利用栈实现简易计算器功能进行详尽解释,此外,我们还将为大家带来关于AndroidStudio实现简易计算器App(Jav

本文将分享Java怎么利用栈实现简易计算器功能的详细内容,并且还将对java怎么利用栈实现简易计算器功能进行详尽解释,此外,我们还将为大家带来关于Android Studio实现简易计算器App (Java语言版)、Android实现简易计算器功能、C#实现简易计算器、C#实现简易计算器功能(1)(窗体应用)的相关知识,希望对你有所帮助。

本文目录一览:

Java怎么利用栈实现简易计算器功能(java怎么利用栈实现简易计算器功能)

Java怎么利用栈实现简易计算器功能(java怎么利用栈实现简易计算器功能)

一、思路分析

当我们输入一个类似于“7*2+100-5+3-4/2”的简单中缀表达式时,我们的编译器能够利用我们所编写的代码将这个表达式扫描并计算出其结果

在这个表达式中主要有两种元素,一种是数字,一种是符号,那么我们就需要创建两个栈结构存储数据

  • 数栈numStack:存放数

  • 符号栈operStack:存放运算符

1、首先我们需要定义一个index(索引),来遍历我们的表达式

立即学习“Java免费学习笔记(深入)”;

2、如果扫描到一个数字,就直接入数栈

3、如果扫描到一个运算符,那就要分以下几种情况:

3.1、如果当前符号栈为空,就直接入栈

3.2、如果符号栈有运算符,就需要进行比较

如果当前运算符的优先级小于或等于栈中的运算符,就需要从数栈中pop出两个数,在符号栈中pop出一个符号,进行运算,得到结果,入数栈,然后将当前的操作符入符号栈

如果当前运算符的优先级大于栈中的运算符,就直接入符号栈

4、当表达式扫描完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并进行计算

5、最后保留在数栈中的那个数字就是运算的结果

二、代码实现

package com.hsy.stack;

public class Calculator {

    public static void main(String[] args) {
        //根据前面老师思路,完成表达式的运算
        String expression = "7*2+100-5+3-4/2";//如何处理多位数的问题?
        //创建两个栈,数栈,一个符号栈
        ArrayStack2 numStack = new ArrayStack2(10);
        ArrayStack2 operStack = new ArrayStack2(10);
        //定义需要的相关变量
        int index = 0;//用于扫描
        int num1 = 0;
        int num2 = 0;
        int oper = 0;
        int res = 0;
        char ch = ' '; //将每次扫描得到char保存到ch
        String keepNum = ""; //用于拼接 多位数
        //开始while循环的扫描expression
        while(true) {
            //依次得到expression 的每一个字符
            ch = expression.substring(index, index+1).charAt(0);
            //判断ch是什么,然后做相应的处理
            if(operStack.isOper(ch)) {//如果是运算符
                //判断当前的符号栈是否为空
                if(!operStack.isEmpty()) {
                    //如果符号栈有操作符,就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符,就需要从数栈中pop出两个数,
                    //在从符号栈中pop出一个符号,进行运算,将得到结果,入数栈,然后将当前的操作符入符号栈
                    if(operStack.priority(ch) <= operStack.priority(operStack.peek())) {
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = numStack.cal(num1, num2, oper);
                        //把运算的结果如数栈
                        numStack.push(res);
                        //然后将当前的操作符入符号栈
                        operStack.push(ch);
                    } else {
                        //如果当前的操作符的优先级大于栈中的操作符, 就直接入符号栈.
                        operStack.push(ch);
                    }
                }else {
                    //如果为空直接入符号栈..
                    operStack.push(ch); // 1 + 3
                }
            } else { //如果是数,则直接入数栈

                //numStack.push(ch - 48); //? "1+3" &#39;1&#39; => 1
                //分析思路
                //1. 当处理多位数时,不能发现是一个数就立即入栈,因为他可能是多位数
                //2. 在处理数,需要向expression的表达式的index 后再看一位,如果是数就进行扫描,如果是符号才入栈
                //3. 因此我们需要定义一个变量 字符串,用于拼接

                //处理多位数
                keepNum += ch;

                //如果ch已经是expression的最后一位,就直接入栈
                if (index == expression.length() - 1) {
                    numStack.push(Integer.parseInt(keepNum));
                }else{

                    //判断下一个字符是不是数字,如果是数字,就继续扫描,如果是运算符,则入栈
                    //注意是看后一位,不是index++
                    if (operStack.isOper(expression.substring(index+1,index+2).charAt(0))) {
                        //如果后一位是运算符,则入栈 keepNum = "1" 或者 "123"
                        numStack.push(Integer.parseInt(keepNum));
                        //重要的!!!!!!, keepNum清空
                        keepNum = "";

                    }
                }
            }
            //让index + 1, 并判断是否扫描到expression最后.
            index++;
            if (index >= expression.length()) {
                break;
            }
        }

        //当表达式扫描完毕,就顺序的从 数栈和符号栈中pop出相应的数和符号,并运行.
        while(true) {
            //如果符号栈为空,则计算到最后的结果, 数栈中只有一个数字【结果】
            if(operStack.isEmpty()) {
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = numStack.cal(num1, num2, oper);
            numStack.push(res);//入栈
        }
        //将数栈的最后数,pop出,就是结果
        int res2 = numStack.pop();
        System.out.printf("表达式 %s = %d", expression, res2);
    }

}

//先创建一个栈,直接使用前面创建好
//定义一个 ArrayStack2 表示栈, 需要扩展功能
class ArrayStack2 {
    private int maxSize; // 栈的大小
    private int[] stack; // 数组,数组模拟栈,数据就放在该数组
    private int top = -1;// top表示栈顶,初始化为-1

    //构造器
    public ArrayStack2(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    //增加一个方法,可以返回当前栈顶的值, 但是不是真正的pop
    public int peek() {
        return stack[top];
    }

    //栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }
    //栈空
    public boolean isEmpty() {
        return top == -1;
    }
    //入栈-push
    public void push(int value) {
        //先判断栈是否满
        if(isFull()) {
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }
    //出栈-pop, 将栈顶的数据返回
    public int pop() {
        //先判断栈是否空
        if(isEmpty()) {
            //抛出异常
            throw new RuntimeException("栈空,没有数据~");
        }
        int value = stack[top];
        top--;
        return value;
    }
    //显示栈的情况[遍历栈], 遍历时,需要从栈顶开始显示数据
    public void list() {
        if(isEmpty()) {
            System.out.println("栈空,没有数据~~");
            return;
        }
        //需要从栈顶开始显示数据
        for(int i = top; i >= 0 ; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }
    //返回运算符的优先级,优先级是程序员来确定, 优先级使用数字表示
    //数字越大,则优先级就越高.
    public int priority(int oper) {
        if(oper == &#39;*&#39; || oper == &#39;/&#39;){
            return 1;
        } else if (oper == &#39;+&#39; || oper == &#39;-&#39;) {
            return 0;
        } else {
            return -1; // 假定目前的表达式只有 +, - , * , /
        }
    }
    //判断是不是一个运算符
    public boolean isOper(char val) {
        return val == &#39;+&#39; || val == &#39;-&#39; || val == &#39;*&#39; || val == &#39;/&#39;;
    }
    //计算方法
    public int cal(int num1, int num2, int oper) {
        int res = 0; // res 用于存放计算的结果
        switch (oper) {
            case &#39;+&#39;:
                res = num1 + num2;
                break;
            case &#39;-&#39;:
                res = num2 - num1;// 注意顺序
                break;
            case &#39;*&#39;:
                res = num1 * num2;
                break;
            case &#39;/&#39;:
                res = num2 / num1;
                break;
            default:
                break;
        }
        return res;
    }

}
登录后复制

以上就是Java怎么利用栈实现简易计算器功能的详细内容,更多请关注php中文网其它相关文章!

Android Studio实现简易计算器App (Java语言版)

Android Studio实现简易计算器App (Java语言版)

本文实例为大家分享了Android Studio实现简易计算器App的具体代码,供大家参考,具体内容如下

效果演示

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:orientation="vertical">
        <TextView
            android:id="@+id/mini"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="40dp"
            android:text=""
            android:textDirection="rtl"/>
        <TextView
            android:id="@+id/max"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="100dp"
            android:text=""
            android:textDirection="rtl"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="%"
                android:textSize="30dp"
                android:onClick="surplus"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="CE"
                android:textSize="30dp"
                android:onClick="clearce"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="C"
                android:textSize="30dp"
                android:onClick="clearc"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="⇦"
                android:textSize="30dp"
                android:onClick="backsprce"/>
        </LinearLayout>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="1/x"
                android:textSize="30dp"
                android:onClick="reciprocal"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="x²"
                android:textSize="30dp"
                android:onClick="square"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="²√x"
                android:textSize="30dp"
                android:onClick="squareroot"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="÷"
                android:textSize="60dp"
                android:onClick="division"/>
        </LinearLayout>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="7"
                android:textSize="30dp"
                android:onClick="number_7"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="8"
                android:textSize="30dp"
                android:onClick="number_8"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="9"
                android:textSize="30dp"
                android:onClick="number_9"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="×"
                android:textSize="30dp"
                android:onClick="multiplication"/>
        </LinearLayout>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="4"
                android:textSize="30dp"
                android:onClick="number_4"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="5"
                android:textSize="30dp"
                android:onClick="number_5"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="6"
                android:textSize="30dp"
                android:onClick="number_6"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="-"
                android:textSize="30dp"
                android:onClick="subtraction"/>
        </LinearLayout>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="1"
                android:textSize="30dp"
                android:onClick="number_1"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="2"
                android:textSize="30dp"
                android:onClick="number_2"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="3"
                android:textSize="30dp"
                android:onClick="number_3"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="+"
                android:textSize="30dp"
                android:onClick="addition"/>
        </LinearLayout>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="±"
                android:textSize="30dp"
                android:onClick="change"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="0"
                android:textSize="30dp"
                android:onClick="number_0"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="."
                android:textSize="30dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="="
                android:textSize="30dp"
                android:onClick="equal"/>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

Java文件

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class MainActivity extends Activity {

    private TextView tv1;
    private TextView tv2;
    private StringBuilder viewStr;
    private int index = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_calc);
        tv1 = (TextView) findViewById(R.id.mini);
        tv2 = (TextView) findViewById(R.id.max);
        viewStr = new StringBuilder();
        index = 0;
    }

    //加减乘除、求余简单运算方法
    public String calc(StringBuilder strB) {
        String allS = strB.toString();
        String[] asmd = {"+","-","×","÷","%"};
        int x = 0; int y = 0;
        String result = null;
        for (int i = 0; i < 5; i ++) {
            int inde = strB.indexOf(asmd[i]);
            if (inde > 0) {
                String a = allS.split(asmd[i])[0];
                String b = allS.split(asmd[i])[1];
                if (i == 0) {result = String.valueOf(Integer.parseInt(a) + Integer.parseInt(b));}
                if (i == 1) {result = String.valueOf(Integer.parseInt(a) - Integer.parseInt(b));}
                if (i == 2) {result = String.valueOf(Integer.parseInt(a) * Integer.parseInt(b));}
                if (i == 3) {
                    if (Integer.parseInt(b) == 0) {
                        Toast.makeText(this,"0不能为除数",Toast.LENGTH_SHORT).show();
                        result = String.valueOf(Integer.parseInt(a));
                    }else {
                        result = String.valueOf(Integer.parseInt(a) / Integer.parseInt(b));
                    }
                }
                if (i == 4) {result = String.valueOf(Integer.parseInt(a) % Integer.parseInt(b));}
            }
        }
        return result;
    }

    //数字按钮事件
    public void number_0(View view) { viewStr.append("0"); index ++ ; tv2.setText(viewStr); }
    public void number_1(View view) { viewStr.append("1"); index ++ ; tv2.setText(viewStr); }
    public void number_2(View view) { viewStr.append("2"); index ++ ; tv2.setText(viewStr); }
    public void number_3(View view) { viewStr.append("3"); index ++ ; tv2.setText(viewStr); }
    public void number_4(View view) { viewStr.append("4"); index ++ ; tv2.setText(viewStr); }
    public void number_5(View view) { viewStr.append("5"); index ++ ; tv2.setText(viewStr); }
    public void number_6(View view) { viewStr.append("6"); index ++ ; tv2.setText(viewStr); }
    public void number_7(View view) { viewStr.append("7"); index ++ ; tv2.setText(viewStr); }
    public void number_8(View view) { viewStr.append("8"); index ++ ; tv2.setText(viewStr); }
    public void number_9(View view) { viewStr.append("9"); index ++ ; tv2.setText(viewStr); }

    //回退按钮事件
    public void backsprce(View view) {
        if (viewStr.length() == 0) return;
        index = viewStr.length();
        viewStr.deleteCharAt(--index); tv2.setText(viewStr);
    }

    //符号改变按钮事件
    public void change(View view) {
        String allS = viewStr.toString();
        String[] asmd = {"+","-","×","÷","%"};
        int inde = 0;
        String a = null;    //保存字符串中运算符部分
        String b = null;    //保存字符串中数字部分
        for (int i = 0; i < 5; i ++) {
            inde = viewStr.indexOf(asmd[i]);
            if (inde != -1) {
                a = asmd[i];
                break;
            }
        }
        //A 字符形 改变 A 正负值
        if (inde == -1) {
            clearc(view);
            int c = - Integer.parseInt(allS);
            viewStr.append(String.valueOf(c));
            index = String.valueOf(c).length();
            tv2.setText(viewStr);
        }
        //A + 字符串形 改变 A 正负值 暂时无法实现,待后续优化
        if (inde == index - 1) {
            return;
//            clearc(view);
//            int c = - Integer.valueOf(allS.split(a)[0]);
//            viewStr.append(String.valueOf(c));
//            index = String.valueOf(c).length();
//            tv2.setText(viewStr);
        }
        //A + B 字符串形 改变 B 正负值
        if (inde >= 0 && inde < index) {
            clearc(view);
            b = allS.split(a)[0];
            int c = - Integer.parseInt(allS.split(a)[1]);
            viewStr.append(b).append(a).append(String.valueOf(c));
            index = String.valueOf(c).length();
            tv2.setText(viewStr);
        }
    }

    //清空按钮事件
    public void clearc(View view) {
        StringBuilder temp = new StringBuilder();
        viewStr = temp.append("");
        tv2.setText(viewStr);
        index = 0;
    }
    public void clearce(View view) {
        StringBuilder temp = new StringBuilder();
        viewStr = temp.append("");
        tv1.setText("");
        tv2.setText(viewStr);
        index = 0;
    }

    //等于按钮事件
    public void equal(View view) {
        String[] asmd = {"+","-","×","÷","%"};
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < 5; i ++) {
            int inde = viewStr.indexOf(asmd[i]);
            if (inde > 0 && inde != index-1) {
                tv1.setText(calc(viewStr));
                String a = calc(viewStr);
                viewStr = temp.append(a);
                tv2.setText(viewStr);
                index = viewStr.length();
                return;
            }else if (inde > 0 && inde == index-1) {
                viewStr.deleteCharAt(--index);
                tv1.setText(viewStr);
                tv2.setText(viewStr);
            }
        }
        tv1.setText(viewStr);
        tv2.setText(viewStr);
    }

    //加减乘除按钮事件
    public void addition(View view) {
        if (viewStr.length() == 0) return;
        String[] asmd = {"+","-","×","÷","%"};
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < 5; i ++) {
            int inde = viewStr.indexOf(asmd[i]);
            if (inde > 0 && viewStr.charAt(index-1) >= ''0'' && viewStr.charAt(index-1) <= ''9'') {
                tv1.setText(calc(viewStr));
                String a = calc(viewStr);
                viewStr = temp.append(a).append(''+'');
                tv2.setText(viewStr);
                index = viewStr.length();
                return;
            }
        }
        char a = viewStr.charAt(index-1);
        if (a == ''+'') { return; }
        if (a == ''-'' || a == ''×'' || a == ''÷'' || a == ''%'') {
            viewStr.setCharAt(index-1,''+'');
        }else {
            viewStr.append("+");
            index ++ ;
        }
        tv2.setText(viewStr);
    }
    public void subtraction(View view) {
        if (viewStr.length() == 0) return;
        String[] asmd = {"+","-","×","÷","%"};
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < 5; i ++) {
            int inde = viewStr.indexOf(asmd[i]);
            if (inde > 0 && viewStr.charAt(index-1) >= ''0'' && viewStr.charAt(index-1) <= ''9'') {
                tv1.setText(calc(viewStr));
                String a = calc(viewStr);
                viewStr = temp.append(a).append(''-'');
                tv2.setText(viewStr);
                index = viewStr.length();
                return;
            }
        }
        char a = viewStr.charAt(index-1);
        if (a == ''-'') { return; }
        if (a == ''+'' || a == ''×'' || a == ''÷'' || a == ''%'') {
            viewStr.setCharAt(index-1,''-'');
        }else {
            viewStr.append("-");
            index ++ ;
        }
        tv2.setText(viewStr);
    }
    public void multiplication(View view) {
        if (viewStr.length() == 0) return;
        String[] asmd = {"+","-","×","÷","%"};
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < 5; i ++) {
            int inde = viewStr.indexOf(asmd[i]);
            if (inde > 0 && viewStr.charAt(index-1) >= ''0'' && viewStr.charAt(index-1) <= ''9'') {
                tv1.setText(calc(viewStr));
                String a = calc(viewStr);
                viewStr = temp.append(a).append(''×'');
                tv2.setText(viewStr);
                index = viewStr.length();
                return;
            }
        }
        char a = viewStr.charAt(index-1);
        if (a == ''×'') { return; }
        if (a == ''+'' || a == ''-'' || a == ''÷'' || a == ''%'') {
            viewStr.setCharAt(index-1,''×'');
        }else {
            viewStr.append("×");
            index ++ ;
        }
        tv2.setText(viewStr);
    }
    public void division(View view) {
        if (viewStr.length() == 0) return;
        String[] asmd = {"+","-","×","÷","%"};
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < 5; i ++) {
            int inde = viewStr.indexOf(asmd[i]);
            if (inde > 0 && viewStr.charAt(index-1) >= ''0'' && viewStr.charAt(index-1) <= ''9'') {
                tv1.setText(calc(viewStr));
                String a = calc(viewStr);
                viewStr = temp.append(a).append(''÷'');
                tv2.setText(viewStr);
                index = viewStr.length();
                return;
            }
        }
        char a = viewStr.charAt(index-1);
        if (a == ''÷'') { return; }
        if (a == ''+'' || a == ''-'' || a == ''×'' || a == ''%'') {
            viewStr.setCharAt(index-1,''÷'');
        }else {
            viewStr.append("÷");
            index ++ ;
        }
        tv2.setText(viewStr);
    }

    //求余按钮事件
    public void surplus(View view) {
        if (viewStr.length() == 0) return;
        String[] asmd = {"+","-","×","÷","%"};
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < 5; i ++) {
            int inde = viewStr.indexOf(asmd[i]);
            if (inde > 0 && viewStr.charAt(index-1) >= ''0'' && viewStr.charAt(index-1) <= ''9'') {
                tv1.setText(calc(viewStr));
                String a = calc(viewStr);
                viewStr = temp.append(a).append(''%'');
                tv2.setText(viewStr);
                index = viewStr.length();
                return;
            }
        }
        char a = viewStr.charAt(index-1);
        if (a == ''%'') { return; }
        if (a == ''+'' || a == ''-'' || a == ''×'' || a == ''÷'') {
            viewStr.setCharAt(index-1,''%'');
        }else {
            viewStr.append("%");
            index ++ ;
        }
        tv2.setText(viewStr);
    }

    //求倒数按钮事件
    public void reciprocal(View view) {
        if (viewStr.length() == 0) return;
        String[] asmd = {"+","-","×","÷","%"};
        for (int i = 0; i < 5; i ++) {
            int inde = viewStr.indexOf(asmd[i]);
            if (inde > -1) { return; }
        }
        int a = Integer.parseInt(viewStr.toString().trim());
        if (a == 0) {
            Toast.makeText(this,"0不能为除数",Toast.LENGTH_SHORT).show();
            return;
        }
        clearc(view);
        viewStr.append(1/a);
        index = String.valueOf(1/a).length();
        tv2.setText(viewStr);
    }

    //平方按钮事件
    public void square(View view) {
        if (viewStr.length() == 0) return;
        String[] asmd = {"+","-","×","÷","%"};
        for (int i = 0; i < 5; i ++) {
            int inde = viewStr.indexOf(asmd[i]);
            if (inde > -1) { return; }
        }
        int a = Integer.parseInt(viewStr.toString().trim());
        clearc(view);
        viewStr.append(a*a);
        index = String.valueOf(a*a).length();
        tv2.setText(viewStr);
    }

    //开平方按钮事件
    public void squareroot(View view) {
        if (viewStr.length() == 0) return;
        String[] asmd = {"+","-","×","÷","%"};
        for (int i = 0; i < 5; i ++) {
            int inde = viewStr.indexOf(asmd[i]);
            if (inde > -1) { return; }
        }
        int a = Integer.parseInt(viewStr.toString().trim());
        clearc(view);
        viewStr.append((int)Math.sqrt(a));
        index = String.valueOf((int)Math.sqrt(a)).length();
        tv2.setText(viewStr);
    }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • Android Java crash 处理流程详解
  • Android性能优化之捕获java crash示例解析
  • Java与Android使用监听者模式示例
  • android studio实现上传图片到java服务器
  • Android Rxjava3 使用场景详解
  • packages思维及使用Java添加Android平台特定实现

Android实现简易计算器功能

Android实现简易计算器功能

本项目为大家分享了Android实现计算器功能的具体代码,供大家参考,具体内容如下

项目介绍

练手项目。能实现加减乘除及括号运算。

开发思路

界面布局

 1.界面布局分三大块:公式文本区、结果文本区、按钮区。
 2.通过点击按钮录入数学公式,实时展示在公式文本区。
 3.点击等号,计算结果展示在结果文本区。
 4.另外还有清空数据和删除一个字符功能。

计算逻辑

 1.将中缀表达式转换为后缀表达式
 2.计算后缀表达式得出结果

其他说明

栈数据结构简单说明:

 1.栈数据结构像弹夹一样,先压进去的子弹后打出来,后压进去的子弹先打出来
 2.入栈:将元素放进栈里,并改变栈顶指针
 3.出栈:将元素从栈里拿出来,并改变栈顶指针
 4.查看栈顶,取得栈顶元素,但不改变栈顶指针

中缀表达式转后缀表达式简单说明

 1.如果是数字,直接放进后缀表达式里。

 2.如果是左括号,入栈。

 3.如果是右括号,依次出栈(放到后缀表达式里),直到遇到左括号。

 4.运算符号:

  1).空栈或栈顶是左括号,入栈
  2).栈顶符号优先级比当前符号小,入栈
  3).栈顶符号优先级大于等于当前符号,依次出栈(放到后缀表达式里),直到遇到不满足条件的元素或栈被掏空。

 5.最后如果栈还有符号,依次出栈(放到后缀表达式里)

后缀表达式计算简单说明

 1.如果是数字,入栈
 2.如果是运算符,将栈顶的两个数字弹出并计算(先出栈的数字放在运算符后面进行计算),再将计算结果入栈。

代码

界面代码

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/the_expression"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="right"
            android:textSize="50dp" />
    </LinearLayout>

    <View
        android:layout_width="wrap_content"
        android:layout_height="2dp"
        android:background="#000" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/the_result"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="right"
            android:textSize="50dp" />
    </LinearLayout>

    <View
        android:layout_width="wrap_content"
        android:layout_height="2dp"
        android:background="#000" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/left_bracket"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="("
            android:textSize="30sp" />

        <Button
            android:id="@+id/right_bracket"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text=")"
            android:textSize="30sp" />

        <Button
            android:id="@+id/clear"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="C"
            android:textSize="30sp" />

        <Button
            android:id="@+id/delete"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="DEL"
            android:textSize="30sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/seven"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="7"
            android:textSize="30sp" />

        <Button
            android:id="@+id/eight"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="8"
            android:textSize="30sp" />

        <Button
            android:id="@+id/nine"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="9"
            android:textSize="30sp" />

        <Button
            android:id="@+id/substraction"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="-"
            android:textSize="30sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/four"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="4"
            android:textSize="30sp" />

        <Button
            android:id="@+id/five"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="5"
            android:textSize="30sp" />

        <Button
            android:id="@+id/six"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="6"
            android:textSize="30sp" />

        <Button
            android:id="@+id/add"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="+"
            android:textSize="30sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/one"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="1"
            android:textSize="30sp" />

        <Button
            android:id="@+id/two"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="2"
            android:textSize="30sp" />

        <Button
            android:id="@+id/three"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="3"
            android:textSize="30sp" />

        <Button
            android:id="@+id/division"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="÷"
            android:textSize="30sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/zero"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="0"
            android:textSize="30sp" />

        <Button
            android:id="@+id/point"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="."
            android:textSize="30sp" />

        <Button
            android:id="@+id/equal"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="="
            android:textSize="30sp" />

        <Button
            android:id="@+id/mulitipliction"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="×"
            android:textSize="30sp" />

    </LinearLayout>
</LinearLayout>

后台逻辑

package com.example.calc;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.calc.utils.Stack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    static final String ADD_TEXT = "+";
    static final String SUBSTRACTION_TEXT = "-";
    static final String MULTIPLICATION_TEXT = "×";
    static final String DIVISION_TEXT = "÷";
    static final String LEFT_BRACKET_TEXT = "(";
    static final String RIGHT_BRACKET_TEXT = ")";
    //符号集合
    static final List<String> SYMBOLS = Arrays.asList(ADD_TEXT, SUBSTRACTION_TEXT, MULTIPLICATION_TEXT, DIVISION_TEXT, LEFT_BRACKET_TEXT, RIGHT_BRACKET_TEXT);
    //符号优先级
    static final Map<String, Integer> SYMBOL_PRIORITY_LEVEL = new HashMap<String, Integer>(4) {{
        put(ADD_TEXT, 1);
        put(SUBSTRACTION_TEXT, 1);
        put(MULTIPLICATION_TEXT, 2);
        put(DIVISION_TEXT, 2);
    }};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        TextView expTextView = findViewById(R.id.the_expression);
        TextView resultTextView = findViewById(R.id.the_result);
        //数字与运算符按钮
        int[] ids = {R.id.zero, R.id.one, R.id.two, R.id.three, R.id.four, R.id.five, R.id.six, R.id.seven, R.id.eight, R.id.nine, R.id.point, R.id.add, R.id.substraction, R.id.mulitipliction, R.id.division, R.id.left_bracket, R.id.right_bracket};
        for (int id : ids) {
            findViewById(id).setOnClickListener((v) -> {
                String newText = expTextView.getText().toString() + ((Button) v).getText().toString();
                expTextView.setText(newText);
            });
        }
        //删除一个字符
        findViewById(R.id.delete).setOnClickListener((v) -> {
            CharSequence text = expTextView.getText();
            if (text != null && text.length() > 0) {
                if (text.length() == 1) {
                    expTextView.setText(null);
                } else {
                    expTextView.setText(text.subSequence(0, text.length() - 1));
                }
            }
        });
        //清理
        findViewById(R.id.clear).setOnClickListener((v) -> {
            expTextView.setText(null);
            resultTextView.setText(null);
        });
        //等于
        findViewById(R.id.equal).setOnClickListener((v) -> {
            List<String> infix = getInfix(expTextView.getText().toString());
            List<String> suffix = infixToSuffix(infix);
            Double result1 = getResult(suffix);
            String result = String.valueOf(result1);
            if (result.contains(".") && result.split("\\.")[1].replace("0", "").length() == 0) {
                result = result.split("\\.")[0];
            }
            resultTextView.setText(result);
        });
    }

    //字符串转中缀表达式
    private List<String> getInfix(String exp) {
        List<String> texts = new ArrayList<>();
        char[] chars = exp.toCharArray();
        StringBuilder sText = new StringBuilder();
        for (char c : chars) {
            String text = String.valueOf(c);
            if (SYMBOLS.contains(text)) {
                if (sText.length() > 0) {
                    texts.add(sText.toString());
                    sText.delete(0, sText.length());
                }
                texts.add(text);
            } else {
                sText.append(text);
            }
        }
        if (sText.length() > 0) {
            texts.add(sText.toString());
            sText.delete(0, sText.length());
        }
        return texts;
    }

    //中缀表达式转后缀表达式
    private List<String> infixToSuffix(List<String> infix) {
        List<String> sufText = new ArrayList<>();
        Stack<String> stack = new Stack<>(infix.size());
        for (String text : infix) {
            if (!SYMBOLS.contains(text)) {
                //数值,直接放到后缀表达式
                sufText.add(text);
            } else if (LEFT_BRACKET_TEXT.equals(text)) {
                //左括号,直接入栈
                stack.push(text);
            } else if (RIGHT_BRACKET_TEXT.equals(text)) {
                //右括号,依次取出栈顶元素放到后缀表达式,直到遇到左括号
                while (!stack.isEmpty()) {
                    String pop = stack.pop();
                    if (!LEFT_BRACKET_TEXT.equals(pop)) {
                        sufText.add(pop);
                    } else {
                        break;
                    }
                }
            } else {
                //其他符号(+-*/)
                buildSuffix(text, sufText, stack);
            }
        }
        //取出剩余栈内数据放到后缀表达式
        while (!stack.isEmpty()) {
            sufText.add(stack.pop());
        }
        return sufText;
    }

    //后缀表达式求结果
    private Double getResult(List<String> suffix) {
        Stack<Double> stack = new Stack<>(suffix.size());
        for (String text : suffix) {
            switch (text) {
                case SUBSTRACTION_TEXT: {
                    Double pop1 = stack.pop();
                    Double pop2 = stack.pop();
                    stack.push(pop2 - pop1);
                    break;
                }
                case ADD_TEXT: {
                    Double pop1 = stack.pop();
                    Double pop2 = stack.pop();
                    stack.push(pop1 + pop2);
                    break;
                }
                case DIVISION_TEXT: {
                    Double pop1 = stack.pop();
                    Double pop2 = stack.pop();
                    stack.push(pop2 / pop1);
                    break;
                }
                case MULTIPLICATION_TEXT: {
                    Double pop1 = stack.pop();
                    Double pop2 = stack.pop();
                    stack.push(pop1 * pop2);
                    break;
                }
                default:
                    stack.push(Double.valueOf(text));
                    break;
            }
        }
        return stack.pop();
    }

    private void buildSuffix(String symbol, List<String> suffix, Stack<String> stack) {
        if (stack.isEmpty()) {
            //是空栈符号直接入栈
            stack.push(symbol);
        } else {
            //栈顶查看
            String peek = stack.peek();
            //栈顶是左括号符号或当前符号优先级大于栈顶符号直接入栈
            if (LEFT_BRACKET_TEXT.equals(peek) || isGreaterThanLevel(symbol, peek)) {
                stack.push(symbol);
            } else {
                //栈顶不是左括号,依次取出比当前符号优先级小或优先级相同的符号放到后缀表达式
                while (!stack.isEmpty()) {
                    if (isLessThanOrEquals(symbol, stack.peek())) {
                        suffix.add(stack.pop());
                    } else {
                        //遇到不符合条件的栈顶数据,直接退出
                        break;
                    }
                }
                //取完数据后,将当前符号入栈
                stack.push(symbol);
            }
        }
    }

    private boolean isGreaterThanLevel(String symbol, String peek) {
        Integer symbolLevel = SYMBOL_PRIORITY_LEVEL.get(symbol);
        Integer peekLevel = SYMBOL_PRIORITY_LEVEL.get(peek);
        return symbolLevel != null && peekLevel != null && symbolLevel > peekLevel;
    }

    private boolean isLessThanOrEquals(String symbol, String peek) {
        Integer symbolLevel = SYMBOL_PRIORITY_LEVEL.get(symbol);
        Integer peekLevel = SYMBOL_PRIORITY_LEVEL.get(peek);
        return symbolLevel != null && peekLevel != null && symbolLevel <= peekLevel;
    }
}

栈数据结构

package com.example.calc.utils;

public class Stack<T> {

    private int size;
    private Object[] elements;
    private int top = -1;

    public Stack(int size) {
        this.size = size;
        elements = new Object[size];
    }

    //压栈
    public void push(T element) {
        if (top != size - 1) {
            elements[top + 1] = element;
            top++;
        } else {
            throw new RuntimeException("stack is full!");
        }
    }

    //弹栈
    public T pop() {
        if (top > -1) {
            top--;
            return (T) elements[top + 1];
        } else {
            throw new RuntimeException("stack is null!");
        }
    }

    //查看栈顶
    public T peek() {
        if (top > -1) {
            return (T) elements[top];
        } else {
            return null;
        }
    }

    public boolean isEmpty(){
        return top == -1;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • 从零开始学android实现计算器功能示例分享(计算器源码)
  • Android开发实现的简单计算器功能【附完整demo源码下载】
  • android计算器简单实现代码
  • Android计算器编写代码
  • android计时器,时间计算器的实现方法
  • Android Studio实现简易计算器
  • Android实现简易计算器小程序
  • Android中使用GridLayout网格布局来制作简单的计算器App
  • android studio实现计算器
  • Android studio设计简易计算器

C#实现简易计算器

C#实现简易计算器

C#编写一个简易计算器,供大家参考,具体内容如下

界面

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;


namespace calculor
{
 public partial class Form1 : Form
 {
 public Form1()
 {
  InitializeComponent();
 }

 //stack<int> nums;
 Stack nums = new Stack();
 //stack<char> ops;
 Stack ops = new Stack();

 //快速幂
 int qmi(int a, int b)
 {
  int res = 1;

  while (b > 0)
  {
  if ((b & 1) == 1) res = res * a;
  a = a * a;
  b >>= 1;
  }

  return res;
 }

 //计算
 void Cal()
 {
  if (nums.Count <= 1)
  {
  if(ops.Count >= 0)
  {
   ops.Pop();
  }
  return;
  }
  double a = (double)nums.Peek(); nums.Pop();
  double b = (double)nums.Peek(); nums.Pop();
  char c = (char)ops.Peek(); ops.Pop();
  double d = 1;
  if (c == ''+'') d = a + b;
  else if (c == ''-'') d = b - a;
  else if (c == ''*'') d = b * a;
  else if (c == ''/'')
  {
  if (a == 0)
  {
   MessageBox.Show("Invliad operator");
   return;  
  }
  else
  {
   d = b / a;
  }
  
  }
  else if (c == ''%'') d = b % a;
  else
  {
  d = Math.Pow(b, a);
  }

  nums.Push(d);
 }

 double Calculate(string str)
 {
  if (str[0] == ''0'') str = ''0'' + str; //-(1 + 1)
  string left = "";
  for (int i = 0; i < str.Length; i++) left += "(";
  str = left + str + ")"; //保证左括号数量大于右括号

  for (int i = 0; i < str.Length; i++)
  {
  if (str[i] >= ''0'' && str[i] <= ''9'')
  {
   int j = i, tmp = 0; //多位数字
   bool flag = false;
   double t = 0;
   while (j < str.Length && ((str[j] >= ''0'' && str[j] <= ''9'') || str[j] == ''.''))
   {
   if(str[j] == ''.'')
   {
    tmp = j;
    j++;
    flag = true;
    continue;
   }
   t = t * 10 + str[j] - ''0'';
   j++;
   }

   i = j - 1;
   if (flag)
   {
   for (int l = 0; l < j - tmp - 1; l++)
   {
    t *= 0.1;
   }
   }
   nums.Push(t);
  }
  else
  {
   char c = str[i];
   if (c == '' '') continue;
   if (c == ''('') ops.Push(c);
   else if (c == ''+'' || c == ''-'')
   {
   if (c == ''-'' && i > 0 && !(str[i - 1] >= ''0'' && str[i - 1] <= ''9'') && str[i - 1] != '')'' && str[i - 1] != '' '') //''-'' 代表负号
   {
    if (str[i + 1] == ''('') // 将-(...)变成-1 * (...)
    {
    nums.Push(-1);
    ops.Push(''*'');
    }
    else
    {
    int j = i + 1, tmp = 0;
    double t = 0;
    bool flag = false;
    while (j < str.Length && ((str[j] >= ''0'' && str[j] <= ''9'') || str[j] == ''.''))
    {
     if (str[j] == ''.'')
     {
     tmp = j;
     j++;
     flag = true;
     continue;
     }
     t = t * 10 + str[j] - ''0'';
     j++;
    }

    i = j - 1;
    if (flag)
    {
     for (int l = 0; l < j - tmp - 1; l++)
     {
     t *= 0.1;
     }
    }
    
    nums.Push(-t);

    
    }
   }
   else //将 + - 号前面的运算符优先级高的结算,加,减优先级最低。前面都可以结算
   {
    while ((char)ops.Peek() != ''('') Cal();
    ops.Push(c);
   }
   }
   else if (c == ''*'' || c == ''/'' || c == ''%'') //将 * / 号前面的运算符优先级高或等于的结算
   {
   while ((char)ops.Peek() == ''*'' || (char)ops.Peek() == ''/'' || (char)ops.Peek() == ''^'' || (char)ops.Peek() == ''%'') Cal();
   ops.Push(c);
   }
   else if (c == ''^'') //将 ''^'' 号前面的运算符优先级高或等于的结算
   {
   while ((char)ops.Peek() == ''^'') Cal();
   ops.Push(c);
   }
   else if (c == '')'') // 将整个括号结算
   {
   while ((char)ops.Peek() != ''('') Cal();
   ops.Pop(); //删除''(''
   }
   //else MessageBox.Show("invalid operator!");
  }


  }

  if(nums.Count != 0) return (double)nums.Peek();

  return -1;

 }


 private void Form1_Load(object sender, EventArgs e)
 {

 }

 private void equal_Click(object sender, EventArgs e)
 {
  string str = txt_Result.Text;
  double res = Calculate(str);
  if (res == -1)
  {
  txt_Result.Text = "";
  return;
  }
  txt_Result.Text = res.ToString();
 }

 private void digitOne_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitOne.Text;
 }

 private void digitTwo_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitTwo.Text;
 }

 private void digitThree_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitThree.Text;
 }

 private void digitFour_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitFour.Text;
 }

 private void digitFive_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitFive.Text;
 }

 private void digitSix_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitSix.Text;
 }

 private void digitZero_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitZero.Text;
 }

 private void digitSeven_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitSeven.Text;
 }

 private void digitEight_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitEight.Text;
 }

 private void digitNine_Click(object sender, EventArgs e)
 {
  txt_Result.Text += digitNine.Text;
 }

 private void cal_Sqrt_Click(object sender, EventArgs e)
 {
  string str = txt_Result.Text;
  double res = Calculate(str);
  if (res == -1)
  {
  txt_Result.Text = "";
  return;
  }
  if (res < 0)
  {
   MessageBox.Show("{数据不合法");
  txt_Result.Text = "";
  return;
  }
  double res1 = Math.Sqrt(res);
  txt_Result.Text = res1.ToString();
 }

 private void Dot_Click(object sender, EventArgs e)
 {
  txt_Result.Text += Dot.Text;
 }

 private void cal_Multi_Click(object sender, EventArgs e)
 {
  txt_Result.Text += cal_Multi.Text;
 }

 private void cal_Sub_Click(object sender, EventArgs e)
 {
  txt_Result.Text += cal_Sub.Text;
 }

 private void cal_Add_Click(object sender, EventArgs e)
 {
  txt_Result.Text += cal_Add.Text;
 }

 private void cal_Rem_Click(object sender, EventArgs e)
 {
  txt_Result.Text += cal_Rem.Text;
 }

 private void left_brack_Click(object sender, EventArgs e)
 {
  txt_Result.Text += left_brack.Text;
 }

 private void right_brack_Click(object sender, EventArgs e)
 {
  txt_Result.Text += right_brack.Text;
 }

 private void cal_log_Click(object sender, EventArgs e)
 {
  string str = txt_Result.Text;
  double res = Calculate(str);
  if (res == -1)
  {
  txt_Result.Text = "";
  return;
  }
  if (res < 0)
  {
  MessageBox.Show("{数据不合法");
  txt_Result.Text = "";
  return;
  }
  double res1 = Math.Log(res);
  txt_Result.Text = res1.ToString();
 }

 private void btn_Clear_Click(object sender, EventArgs e)
 {
  txt_Result.Text = "";
 }

 private void cal_mi_Click(object sender, EventArgs e)
 {
  txt_Result.Text += cal_mi.Text;
 }

 private void cal_Div_Click(object sender, EventArgs e)
 {
  txt_Result.Text += cal_Div.Text;
 }

 private void btn_backspace_Click(object sender, EventArgs e)
 {
  string str = txt_Result.Text;
  string newStr = "";
  int len = str.Length;
  if (len > 0)
  {
  for(int i = 0; i < len - 1; i++)
  {
   newStr += str[i];
  }
  }
  txt_Result.Text = newStr;
 }
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • C#编写的windows计算器的实例代码
  • C#计算器编写代码
  • C#实现简单的计算器功能完整实例
  • C#开发简易winform计算器程序
  • C#实现简单计算器功能
  • C#实现简单加减乘除计算器
  • C#实现Winform版计算器
  • C#实现的简单整数四则运算计算器功能示例
  • c#入门之实现简易存款利息计算器示例
  • C# WinForm程序设计简单计算器

C#实现简易计算器功能(1)(窗体应用)

C#实现简易计算器功能(1)(窗体应用)

本文实例为大家分享了C#实现简易计算器功能的具体代码,供大家参考,具体内容如下

实现页面布局和数值初始化

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsAppCalculator
{
    public partial class Form1 : Form
    {
        double number = 0;
        public Form1()
        {
            InitializeComponent();
        }


        private void num1_Click(object sender, EventArgs e)
        {
            number = number * 10 + 1;
            labelout.Text = Convert.ToString(number);
        }

        private void num2_Click(object sender, EventArgs e)
        {
            number = number * 10 + 2;
            labelout.Text = Convert.ToString(number);
        }

        private void num3_Click(object sender, EventArgs e)
        {
            number = number * 10 + 3;
            labelout.Text = Convert.ToString(number);
        }
        private void num4_Click(object sender, EventArgs e)
        {
            number = number * 10 + 4;
            labelout.Text = Convert.ToString(number);
        }

        private void num5_Click(object sender, EventArgs e)
        {
            number = number * 10 + 5;
            labelout.Text = Convert.ToString(number);
        }

        private void num6_Click(object sender, EventArgs e)
        {
            number = number * 10 + 6;
            labelout.Text = Convert.ToString(number);
        }

        private void num7_Click(object sender, EventArgs e)
        {
            number = number * 10 + 7;
            labelout.Text = Convert.ToString(number);
        }

        private void num8_Click(object sender, EventArgs e)
        {
            number = number * 10 + 8;
            labelout.Text = Convert.ToString(number);
        }

        private void num9_Click(object sender, EventArgs e)
        {
            number = number * 10 + 9;
            labelout.Text = Convert.ToString(number);
        }

        private void num0_Click(object sender, EventArgs e)
        {
            number = number * 10 + 0;
            labelout.Text = Convert.ToString(number);
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            labelout.Text = Convert.ToString(number);
        }

        private void clean_Click(object sender, EventArgs e)
        {
            number = 0;
            labelout.Text = Convert.ToString(number);
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • C#计算器编写代码
  • C#编写的windows计算器的实例代码
  • C#开发简易winform计算器程序
  • C#实现简单的计算器功能完整实例
  • C#实现简单计算器功能
  • C#实现简单加减乘除计算器
  • C#实现Winform版计算器
  • C#实现的简单整数四则运算计算器功能示例
  • c#入门之实现简易存款利息计算器示例
  • C# WinForm程序设计简单计算器

今天的关于Java怎么利用栈实现简易计算器功能java怎么利用栈实现简易计算器功能的分享已经结束,谢谢您的关注,如果想了解更多关于Android Studio实现简易计算器App (Java语言版)、Android实现简易计算器功能、C#实现简易计算器、C#实现简易计算器功能(1)(窗体应用)的相关知识,请在本站进行查询。

本文标签: