简体   繁体   中英

Prefix Expression Evaluation(Using Stacks)-Java

I have a question about my method that is supposed to evaluate prefix expressions. I have gotten it to work for post fix expressions using stacks so I figured that it should be similar. I need to read from right to left rather than left to right. Here is my method for evaluating, any suggestions or pointers would be greatly appreciated:

// evaluates a preFix expression
public static int evaluate(String input)
{
    int number, leftOperand, rightOperand, result;
    char operator;
    String token;

    // create an integer stack
    Stack<Integer> stack = new Stack<Integer>();

    // create string tokenizer containing string input
    StringTokenizer tokenizer = new StringTokenizer(input);

    // while input string has more tokens
    while (tokenizer.hasMoreTokens()) {
        token = tokenizer.nextToken();// get next token
        // if token is character
        if (isChar(token)) {
            number = Integer.parseInt(token);// push into stack
            stack.push(number);
        // if token is operator
        } else {
            operator = token.charAt(0);// get operator
            rightOperand = stack.pop();// pop two numbers
            leftOperand = stack.pop();
            result = evaluate(rightOperand, leftOperand, operator);// evaluate
            stack.push(result);// push result
        }
    }
    return stack.pop();// final answer

Exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:572)
at java.lang.Integer.parseInt(Integer.java:615)
at PrefixEvaluator.evaluate(PrefixEvaluator.java:40)
at PrefixEvaluator.main(PrefixEvaluator.java:99)

The NumberFormatException says that you tried to parse '-' as a number. So there must be something wrong with the code you didn't post that decides whether a token is a number or an operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM