Мне нужна помощь в создании кода драйвера для Postfix - PullRequest
0 голосов
/ 27 октября 2019

import java.util.EmptyStackException;

import java.util.Stack;

открытый класс PostfixEvaluator {

//The operand Stack
Stack<Integer> operandStack; 

//The operators
String OPERATORS = "*/-+";

// Метод должен оценивать выражение постфиксаpublic int eval (строковое выражение) выдает исключение {

    //creates a string array that 
    //contains expression which is split into individual strings 
    //depending on the spacing
    String [] tokens = expression.split("\\s+");

    try {
        //enhanced for loop that loops through string array tokens
        for (String newToken : tokens) {

            char c = newToken.charAt(0);

            //checks if nextToken starts with a digit
            if(Character.isDigit(c)) {
                //if it is a digit then we convert
                //the char to integer as value
                int value = Integer.parseInt(newToken);
                //pushes the value into the integer operand stack
                operandStack.push(value);
            }
            //if the first character is an operator
            else if (isOperator(c)) {
                //evaluates the operator using the evalOp method
                int i = evalOp(c);
                //pushes the result back to the stack
                operandStack.push(i);
        }
            else {
                //if the character is neither a digit nor operator
                throw new Exception("Invalid character encountered: " + c);
            }


        }

        //when there are no more tokens
        //we pop the result from the operand stack
        int result = operandStack.pop();
        //stack should be empty since there are no more tokens
        if(operandStack.empty()) {
            //returns the final result 
            return result;
        }
        else {
            //if operand stack is not empty
            throw new Exception("Stack should be empty");
        }


    }
    catch(EmptyStackException ex) {
        //if the stack is empty and trying to use pop();
        throw new Exception("The stack is empty");
    }
}


private int evalOp(char op) {
    //pops the right and left operand off the stack
    int right = operandStack.pop();
    int left = operandStack.pop();
    int answer = 0;


    //evaluates the operator depending on case
    switch(op) {
    case '+' : answer = left + right;
               break;
    case '-' : answer = left - right;
               break;
    case '/' : answer = left / right;
               break;
    case '*' : answer = left * right;
               break;
    }
    //answer after evaluating with operator
    return answer;  

}

private boolean isOperator(char ch) {
    //true when the character is an operator
    return OPERATORS.indexOf(ch) != -1;
}

}

, когда я создал код драйвера, я создал строку s = "4 7 *";и попытался оценить это, используя eval (s);но произошла ошибка и не удалось использовать код. Может ли кто-нибудь помочь мне в том, что я сделал неправильно, спасибо

...