修复后计算器

时间:2015-03-05 19:35:33

标签: java stack

我的代码工作正常并按Enter键计算。

问题 - 当我输入=(等于)查看结果时,你能帮我吗?其他

比按下输入!感谢

package bob;
import java.util.Scanner;

public class book {

public static void main(String[] args) 
{

    String expression, again;
    int result;

    Scanner in = new Scanner(System.in);

    do
    {  
        Post fix Evaluate evaluate = new  post fix Evaluate();
        System. out. print Ln("Enter a valid post-fix expression one token " +"at a time with a space between each token (e.g. 5 4 + 3 2 1 - + *)");
        System. out. print Ln("Each token must be an integer or an operator (+,-,*,/)");
        expression = in. next Line();

        result = evaluate. (expression);
        System. out. print Ln();
        System. out. print Ln("That expression equals " + result);

        System.out.print("Evaluate another expression [Y/N]? ");
        again = in. next Line();
        System. out. print Ln();
    }
    while (again. equals Ignore Case("y"));
}
}

package bob;
import java.util.Stack;
import java.util.Scanner;
public class Post fix Evaluate 
{
private final static char ADD = '+';
private final static char SUBTRACT = '-';
private final static char MULTIPLY = '*';
private final static char DIVIDE = '/';
private Stack<Integer> stack;

/**
 * Sets up this evaluate by creating a new stack.
 */
public Post fix Evaluate()
{
    stack = new Stack<Integer>();
}
public int evaluate(String exp)
{
    int op 1, op 2, result = 0;
    String token;
    Scanner parser = new Scanner(exp);

    while (parser. has Next())
    {
        token = parser.next();

        if (is Operator(token))
        {
            op 2 = (stack.pop()).int Value();
            op 1 = (stack.pop()).int Value();
            result = extraterritoriality(token. char At(0), op 1, op 2);
            stack.push(new Integer(result));
        }
        else
            stack.push(new Integer(Integer. parse Int (token)));
    }

    return result;
}
private Boolean is Operator(String token)
{
    return ( token.equals("+") || token.equals("-") ||
             token.equals("*") || token.equals("/") );
}

private int extraterritoriality(char operation, int op 1, int op 2)
{
    int result = 0;

    switch (operation)
    {
        case ADD:
            result = op 1 + op 2;
            break;
        case SUBTRACT:
            result = op 1 - op 2;
            break;
        case MULTIPLY:
            result = op 1 * op 2;
            break;
        case DIVIDE:
            result = op 1 / op 2;
    }

    return result;
}

0 个答案:

没有答案