java-表达式求值

程序小白,希望和大家多交流,共同学习

//用后缀是计算表达式的值

import java.util.Scanner;

public class Operation_LinkedList{
    private static GenericLinkedList<Integer> digitStack = new GenericLinkedList<>();
    private static GenericLinkedList<Character> operatorStack = new GenericLinkedList<>();
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        //读取表达式,然后判断表达式是否合法,最后计算
        while (true){
            System.out.println("输入表达式:");
            String operation = input.nextLine();
            if (!isLegal(operation)){
                System.out.println("请检查表达式,重新输入");
            }
            else{
                try{
                    int result = compute(operation);
                    System.out.println(result);
                }
                catch (ArithmeticException ex){
                    System.out.println(ex);
                }
            }
        }
    }

    public static boolean isLegal(String operation){
        //允许输入的字符+-*/^()123456789=
        //非法状况有:括号左右不匹配,左括号,加1,右括号,减一。此过程只能出现1或0
        //连续出现多个运算符+-*/^
        //等于号出现过早
        String str = "+-*/^()1234567890=";
        String op = "+-*/^";
        int len = operation.length();
        int count = 0;//括号匹配
        char ch = ' ';
        for (int i = 0; i < len - 1; i++){
            ch = operation.charAt(i);
            if (!operation.contains(ch + "")){
                System.out.println("非法字符" + ch);
                return false;
            }

            if (ch == '('){
                count += 1;
            }

            if (ch == ')'){
                count -= 1;
                if (count < 0){
                    System.out.println("括号不匹配,右多");
                    return false;
                }
            }

            if (ch == '='){
                System.out.println("\"=\"位置非法");
                return false;
            }

            if (ch == '/' && operation.charAt(i + 1) == '0'){
                System.out.println("除数不能为零");
                return false;
            }
        }
        if (count > 0){
            System.out.println("括号不匹配,左多");
            return false;
        }

        if (operation.charAt(len - 1) != '='){
            System.out.println("表达式要以\"=\"结尾");
            return false;
        }

        return true;
    }
    public static int compute(String operation){
        //除数为0
        //digitStack、operatorStack
        int result = 0;//记录结果
        StringBuilder n = new StringBuilder("");//数字
        String number = "0123456789";
        operatorStack.push('#');
        int len = operation.length();
        char ch = ' ';
        for (int i = 0; i < len; i++){
            ch = operation.charAt(i);
            //System.out.println(ch);
            //数字使用一个字符串表示,当下一个字符不再是数字的时候,就将已经有的数字字符串转成数字,入栈
            //并将此字符串清空
            if (!number.contains(ch + "")){//是运算符+-*/()
                if (!n.toString().equals("")){
                    digitStack.push(Integer.valueOf(n.toString()));
                    //System.out.println(n);
                    n = new StringBuilder("");
                }
                if (ch == ')'){
                    while ((Character)operatorStack.getTop() != '('){
//                      System.out.println("handle ) " + (Character)operatorStack.getTop());
                        handle();
                    }
                    //System.out.println("handle ) " + (Character)operatorStack.getTop());
                    operatorStack.pop();
                }
                if (ch != '=' && ch != '(' && ch != ')'){
                    while (priority(ch) <= priority((Character)operatorStack.getTop())
                        && (Character)operatorStack.getTop() != '#'){
//                      System.out.println((Character)operatorStack.getTop() + " handle =");
                        handle();
                    }
                    operatorStack.push(ch);
                }
                if (ch == '('){
                    operatorStack.push('(');
                }
            }
            else{
                n.append(ch + "");
            }

            if (ch == '='){
                while ((Character)operatorStack.getTop() != '#')
                {
//                  System.out.println("handle =");
//                  System.out.println((Character)operatorStack.getTop());
                    handle();
                }
                result = (Integer)digitStack.getTop();
            }
        }
        return result;
    }

    public static void handle(){
        int d2 = (Integer)digitStack.getTop();
        digitStack.pop();
        int d1 = (Integer)digitStack.getTop();
        digitStack.pop();
        char op = (Character)operatorStack.getTop();
        operatorStack.pop();
        //System.out.println(d1 + " " + op + " " + d2);
        int result = 0;
        switch (op){
        case '+':
            result = d1 + d2; break;
        case '-':
            result = d1 - d2; break;
        case '*':
            result = d1 * d2; break;
        case '/':
            if (d2 == 0){
                throw new ArithmeticException("运算过程中,除数为零");
            }
            else
            {
                result = d1 / d2; 
                break;
            }
        case '^':
            result = pow(d1, d2);
        }
        //System.out.println("handle" + result);
        digitStack.push(result);
    }

    public static int pow(int n1, int n2){
        int result = 1;
        for (int i = 0; i < n2; i++){
            result *= n1;
        }
        //System.out.println(n1 + " " + n2 + " = " + result);
        return result;
    }
    public static int priority(char ch){
        switch (ch){
        case '#':
            return 0;
        case '(':
            return 1;
        case '+':
        case '-':
            return 2;
        case '*':
        case '/':
            return 3;
        case '^':
            return 4;
        }
        return -1;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值