java 使用双Stack实现一个简单的计算器

package com.bobo.normal;

import com.bobo.util.StringUtil;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * User: bobo
 * Date: 2019/9/16
 * Description: stack实现一个 +-*?的计算器
 * 所得:
 *     去除无效字符的方式
 *     计算器运算过程中符号的优先级优先级 '(' > '*' = '/' > '+' = '-' > ')'
 */
public class Calculate {

    //存储整型数值
    private static Stack<Integer> digitStack = new Stack<>();
    //存储符号
    private static Stack<String> symbolStack = new Stack<>();

    public static int calculate(String string) {
        if(StringUtil.isEmpty(string)){
            return 0;
        }
        //去除无效字符
        //string = string.replaceAll(" +","");
        string = string.replaceAll("\\s*", "");
        //当前的字符
        String currTemp;
        //当前要计算的字符串
        StringBuffer stringBuffer = new StringBuffer().append(string);
        //拼接整型的串
        StringBuffer digitBuffer = new StringBuffer();
        while (stringBuffer.length()>0) {
            currTemp = stringBuffer.substring(0, 1);
            stringBuffer = stringBuffer.delete(0,1);
            if (isDigit(currTemp)) {
                digitBuffer.append(currTemp);
            }else{
                if (digitBuffer.length()>0) {
                    digitStack.push(Integer.parseInt(digitBuffer.toString()));
                    digitBuffer.delete(0,digitBuffer.length());
                }
                //符号需要区分优先级,看是放入栈顶还是进行计算
                while (!symbolPriority(currTemp) && !symbolStack.isEmpty()) {
                    int param2 = digitStack.pop();
                    int param1 = digitStack.pop();
                    switch (symbolStack.pop()){
                        case "*":
                            digitStack.push((param1 * param2));
                            break;
                        case "/":
                            digitStack.push((param1 / param2));
                            break;
                        case "+":
                            digitStack.push((param1+param2));
                            break;
                        case "-":
                            digitStack.push((param1-param2));
                            break;
                        default:break;
                    }
                }
                if (")".equals(currTemp)) {
                    //如果是")",说明括号内已经运算完了,可以去掉前后小括号了
                    symbolStack.pop();
                }else {
                    //
                    symbolStack.push(currTemp);
                }
            }
        }
        return digitStack.pop();
    }

    public static boolean isDigit(String string) {
        return string.matches("[0-9]");
    }

    /**
     * 判断优先级,如果传入的字符的优先级低于符号栈中栈顶的元素,则抛出栈顶元素,计算结果,然后放入此符号
     * 优先级排序 各个优先级'(' > '*' = '/' > '+' = '-' > ')'
     * "#"是结束符,用于最终换算
     * @param string
     * @return
     */
    public static boolean symbolPriority(String string) {
        if (symbolStack.isEmpty()) {
            return true;
        }
        String peek = symbolStack.peek();
        if (peek.equals("(")) {
            return true;
        }
        boolean result =true;
        switch (string){
            case "#":
                result = false;
                break;
            case "(":
                break;
            case ")":
                result = false;
                break;
            case "*":
                if (peek.equals("+") || peek.equals("-")){
                    result = true;
                }else {
                    result = false;
                }
                break;
            case "/":
                if (peek.equals("+") || peek.equals("-")){
                    result = true;
                }else {
                    result = false;
                }
                break;
            case "+":
                result = false;
                break;
            case "-":
                result = false;
                break;
             default:
                 result = true;
                 break;
        }
        return result;
    }


    public static void main(String[] args) {
        /*String str = " a ,hello    world         !!!  ";
        //str = str.replaceAll(" +","");
        str = str.replaceAll("\\s*", "");
        System.out.println("str = " + str);*/
        //String str = "3 + (3+4*5)/2  #";//14
        String str = "(3+4*(4*10-10/2)#";//143
        int calculate = calculate(str);
        System.out.println("str = " + calculate);
    }
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这个问题非常适合用程序解决。以下是用stack实现简单计算器的c代码示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define STACKLEN 1000 /* 栈的最大容量 */ typedef struct { int top; /* 栈顶指针 */ double data[STACKLEN]; /* 元素数组 */ } Stack; void push(Stack *pstack, double value) { if (pstack->top == STACKLEN - 1) { printf("Error: stack overflow!\n"); exit(EXIT_FAILURE); } else { pstack->data[++pstack->top] = value; } } double pop(Stack *pstack) { if (pstack->top == -1) { printf("Error: stack underflow!\n"); exit(EXIT_FAILURE); } else { return pstack->data[pstack->top--]; } } bool is_digit(char c) { return (c >= '0' && c <= '9'); } int precedence(char op) { if (op == '+' || op == '-') return 1; else if (op == '*' || op == '/') return 2; else return 0; } double calculate(double left, char op, double right) { switch (op) { case '+': return left + right; case '-': return left - right; case '*': return left * right; case '/': return left / right; default: printf("Error: invalid operator!\n"); exit(EXIT_FAILURE); } } double eval(char *expr) { Stack operandStack; operandStack.top = -1; Stack operatorStack; operatorStack.top = -1; int len = strlen(expr); int i = 0; while (i < len) { char c = expr[i]; if (is_digit(c)) { double value = 0.0; while (i < len && is_digit(expr[i])) { value = value * 10.0 + (double)(expr[i] - '0'); i++; } push(&operandStack, value); } else { while (operatorStack.top != -1 && precedence(operatorStack.data[operatorStack.top]) >= precedence(c)) { char op = operatorStack.data[operatorStack.top--]; double right = pop(&operandStack); double left = pop(&operandStack); push(&operandStack, calculate(left, op, right)); } push(&operatorStack, c); i++; } } while (operatorStack.top != -1) { char op = operatorStack.data[operatorStack.top--]; double right = pop(&operandStack); double left = pop(&operandStack); push(&operandStack, calculate(left, op, right)); } return pop(&operandStack); } int main() { char s[1000]; printf("Please enter an expression: "); scanf("%s", s); double result = eval(s); printf("Result: %f\n", result); return 0; } ``` 这段代码定义了两个栈:一个操作数栈(operandStack)和一个操作符栈(operatorStack),通过不断入栈和出栈的操作,实现对表达式进行求值。其中,is_digit函数用于判断一个字符是否是数字;precedence函数用于比较两个运算符的优先级;calculate函数用于计算两个操作数和一个操作符的运算结果;eval函数是主函数,用于将输入的表达式转化为数字计算结果。 希望这个回答能够帮助您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值