Java RPN计算器空指针问题

时间:2012-11-22 23:48:39

标签: java calculator rpn

您好我已设法修复空指针问题。

现在我几乎得到了代码工作,除非它正在评估我得到每个等式的答案为15?

我的TestClass如下所示:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class TestClass {

private static final int LEFT_ASSOC = 0;
private static final int RIGHT_ASSOC = 1;
static String OPERATORS1 = "+-*/()";

// Operators
private static final Map<String, int[]> OPERATORS = new HashMap<String, int[]>();
static {
    // Map<"token", []{precedence, associativity}>
    OPERATORS.put("+", new int[] { 2, LEFT_ASSOC });
    OPERATORS.put("-", new int[] { 2, LEFT_ASSOC });
    OPERATORS.put("*", new int[] { 3, LEFT_ASSOC });
    OPERATORS.put("/", new int[] { 3, LEFT_ASSOC });
    OPERATORS.put("(", new int[] {1, RIGHT_ASSOC});
    OPERATORS.put(")", new int[] {1, LEFT_ASSOC});
}

private static boolean isOperator(String token) {
    return OPERATORS.containsKey(token);
}

// Test associativity of operator token
private static boolean isAssociative(String token, int type) {
    if (!isOperator(token)) {
        throw new IllegalArgumentException("Invalid token: " + token);
    }

    if (OPERATORS.get(token)[1] == type) {
        return true;
    }
    return false;
}

// Compare precedence of operators.
private static final int cmpPrecedence(String token1, String token2) {
    if (!isOperator(token1) || !isOperator(token2)) {
        throw new IllegalArgumentException("Invalid tokens: " + token1
                + " " + token2);
    }
    return OPERATORS.get(token1)[0] - OPERATORS.get(token2)[0];
}

public static String[] infixToRPN(String[] inputTokens) {
    myArrayList<String> out = new myArrayList<String>();
    myStack<String> stack = new myStack<String>();
    // For each token
    for (String token : inputTokens) {
        StringTokenizer tokens = new StringTokenizer(token,OPERATORS1,true);
        while (tokens.hasMoreTokens()) {
             token = tokens.nextToken();

        }
        // If token is an operator
        if (isOperator(token)) {
            // While stack not empty AND stack top element
            // is an operator
            while (!stack.isEmpty() && isOperator(stack.peek())) {
                if ((isAssociative(token, LEFT_ASSOC) && cmpPrecedence(
                        token, stack.peek()) <= 0)
                        || (isAssociative(token, RIGHT_ASSOC) && cmpPrecedence(
                                token, stack.peek()) < 0)) {
                    out.add(stack.pop());
                    continue;
                }
                break;
            }
            // Push the new operator on the stack
            stack.push(token);
        }
        // If token is a left bracket '('
        else if (token.equals("(")) {
            stack.push(token); 
        }
        // If token is a right bracket ')'
        else if (token.equals(")")) {
            while (!stack.isEmpty() && !stack.peek().equals("(")) {
                out.add(stack.pop());
            }
            stack.pop();
        }
        // If token is a number
        else {
            out.add(token);
        }
    }
    while (!stack.isEmpty()) {
        out.add(stack.pop());
    }
    String[] output = new String[out.size()];
    return out.toArray(output);
}

public static double RPNtoDouble(String[] tokens) {
    myStack<String> stack = new myStack<String>();

    // For each token
    for (String token : tokens) {
        // If the token is a value push it onto the stack
        if (!isOperator(token)) {
            stack.push(token);
        } else {
            // Token is an operator: pop top two entries
            Double d2 = Double.valueOf(stack.pop());
            Double d1 = Double.valueOf(stack.pop());

            // Get the result
            Double result = token.compareTo("+") == 0 ? d1 + d2 : token
                    .compareTo("-") == 0 ? d1 - d2
                            : token.compareTo("*") == 0 ? d1 * d2 : d1 / d2;

            // Push result onto stack
            stack.push(String.valueOf(result));
        }
    }

    return Double.valueOf(stack.pop());
}

@SuppressWarnings("unused")
static public void main(String[] args) throws IOException {
    File file = new File("testEquations.txt");
    String[] lines = new String[10];

    try {
        FileReader reader = new FileReader(file);
        @SuppressWarnings("resource")
        BufferedReader buffReader = new BufferedReader(reader);
        int x = 0;
        String s;
        while ((s = buffReader.readLine()) != null) {
            lines[x] = s;
            x++;
        }
    } catch (IOException e) {
        System.exit(0);
    }
    // test printing string array
    for (String s : lines) {
        System.out.println("" + s);
        String[] output =infixToRPN(lines);
        System.out.println(RPNtoDouble(output));
    }


    for (String st : lines) {
        if (st != null) {
            StringTokenizer tokens = new StringTokenizer(st,OPERATORS1,true);
            while (tokens.hasMoreTokens()) {
                String token = tokens.nextToken();

            }

        }
    }

}

}

我收到的输出是

49+62*61-36
15.0
4/64
15.0
(53+26)
15.0
0*72
15.0
21-85+75-85
15.0
90*76-50+67
15.0
46*89-15
15.0
34/83-38
15.0
20/76/14+92-15
15.0
5*10/3-1
15.0

这来自以下输入文件:

49+62*61-36
4/64
(53+26)
0*72
21-85+75-85
90*76-50+67
46*89-15
34/83-38
20/76/14+92-15
5*10/3-1

任何帮助将不胜感激。

渴望阅读。

1 个答案:

答案 0 :(得分:0)

如果您的行号正确,则为以下行:

else if (token.equals("(")) {

所以显然令牌是空的。 =&GT;检查这是否是事实,然后看看为什么会这样。