簡體   English   中英

Java中的數學表達式轉換器前綴

[英]Infix To Prefix Mathematical Expression Converter in Java

我正在嘗試編寫一種將Infix轉換為Prefix Mathematical Expression的方法,並為此使用了堆棧。 但是在某些情況下我會出錯,而且我不知道這是什么問題。

碼:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Stack;
import java.util.StringTokenizer;

public class Prefixer {

    public static void main(String[] args) {
        String fileName;
        boolean reduce = false;
        if (args.length == 1){
            fileName = args[0];
        }
        else if (args.length >= 2){
            reduce = args[0].equals("-r");
            fileName = args[1];
        }
        else
        {
            return;
        }
        BufferedReader reader;
        String line = "";
        try {
            reader = new BufferedReader(new FileReader (fileName));
            line = reader.readLine();
            line = line.trim();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(infixToPrefixConvert(line,reduce));
    }

    public static boolean isOperand(String s) {
        return !(s.equals("+") || s.equals("-") || s.equals("/") || s.equals("*") || s.equals("(") || s.equals(")"));
    }

    public static boolean isNumber(String s){
        try {
            Integer.parseInt(s.trim());
        } catch (Exception e){
            return false;
        }
        return true;
    }

    public static String operationCombine(Stack<String> operatorStack, Stack<String> operandStack, boolean reduce){
        String operator = operatorStack.pop();
        String rightOperand = operandStack.pop();
        String leftOperand = operandStack.pop();
        if (reduce && isNumber(rightOperand) && isNumber(leftOperand)){
            int left = Integer.parseInt(leftOperand);
            int right = Integer.parseInt(rightOperand);
            int result = 0;
            if (operator.equals("+")){
                result = left + right;
            }else if (operator.equals("-")){
                result = left - right;
            }else if (operator.equals("*")){
                result = left * right;
            }else if (operator.equals("/")){
                result = left / right;
            }
            return "" + result;

        }
        String operand = "(" + operator + " " + leftOperand + " "+ rightOperand + ")";
        return operand;
    }

    public static int rank(String s) {
        if (s.equals("+") || s.equals("-"))
            return 1;
        else if (s.equals("/") || s.equals("*"))
            return 2;
        else
            return 0;
    }

    public static String infixToPrefixConvert(String infix, boolean reduce) {
        Stack<String> operandStack = new Stack<String>();
        Stack<String> operatorStack = new Stack<String>();

        StringTokenizer tokenizer = new StringTokenizer(infix);
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (isOperand(token)) {
                operandStack.push(token);
            }

            else if (token.equals("(") || operatorStack.isEmpty()
                    || rank(token) > rank(operatorStack.peek())) {
                operatorStack.push(token);
            }

            else if (token.equals(")")) {
                while (!operatorStack.peek().equals("(")) {
                    operandStack.push(operationCombine(operatorStack, operandStack,reduce));
                }
                operatorStack.pop();
            }

            else if( rank(token) <= rank(operatorStack.peek())){
                while(!operatorStack.isEmpty() && rank(token) <= rank(operatorStack.peek())){
                    operandStack.push(operationCombine(operatorStack, operandStack,reduce));
                }
                operatorStack.push(token);
            }
        }
        while( !operatorStack.isEmpty() ) {
            operandStack.push(operationCombine(operatorStack, operandStack,reduce));
        }
        return (operandStack.peek());
    }

}

該文件應該是您要轉換的infix表達式的第一行。 如果要在轉換為前綴時減少簡單的算術表達式,則使用-r標志。 例如在test.txt中,如果我有

3 * 9 + ( 9 + y ) / 4 - x

它工作正常。 但是如果我有

12 / c + c * p ^ ( 8 + 9 )

它應該給我:12 c / cp 8 9 + ^ * +但我得到:(+ p(* ^(+ 8 9)))

問題是什么。 請幫我。 謝謝

瞥一眼您的代碼,我可能會說這行

String operand = "(" + operator + " " + leftOperand + " "+ rightOperand + ")";

是問題的根源,也是您沒有在operationCombine函數中考慮運算符^的事實。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM