Frage

Hi I have managed to fix the null pointer issue.

Now I have almost got the code working except when it is evaluating I am getting the answer for every equation as 15?

My TestClass is shown below:

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();

            }

        }
    }

}

}

and the output i receive is

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

This is from the following input file:

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

any help will be much appreciated.

Thans for reading.

War es hilfreich?

Lösung

If your line numbers are correct this is the line:

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

so obviously token is null. => Check if that is the fact, and then see why it is like that.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top