java Stack的基本使用并且实现一个简单的计算器

本文介绍了Java中Stack<E>类的基本用法,并通过实例展示了如何利用Stack实现一个简单的计算器功能。
摘要由CSDN通过智能技术生成

java.util.Stack<E>的方法

Modifier and TypeMethod and Description
booleanempty()

Tests if this stack is empty.

Epeek()

Looks at the object at the top of this stack without removing it from the stack.

Epop()

Removes the object at the top of this stack and returns that object as the value of this function.

Epush(E item)

Pushes an item onto the top of this stack.

intsearch(Object o)

Returns the 1-based position where an object is on this 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);
    }
}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值