Testing program:
public class Test
{
    public static void main(String[] args)
    {
        String str = "1 + 4";
        new MyClass(str);
    }
}
Problem Code:
import java.util.*;
public class MyClass
{
    public MyClass(String str)
    {
        Stack<String> operators = new Stack<String>();
        Queue<String> output = new LinkedList<String>();
        String[] tokens = str.split("\\s");
        StringBuilder postFixStr = new StringBuilder();
        final String isDigit = "[0-9]";
        final String isOperator = "[(^/*+\\-)]";
        for (int i = 0; i < tokens.length; i++)
        {
            if (tokens[i].matches(isDigit))
            {
                output.offer(tokens[i]);
            }
            else if (tokens[i].matches(isOperator))
            {
                operators.push(tokens[i]);
            }
        }
        output.offer(operators.pop());
        for (int j = 0; j < output.size(); j++)
        {
            postFixStr.append(output.poll());
        }
        System.out.print(postFixStr.toString());
    }
}
Output:
14
The conclusion should be:
14+
If I changed:
final String isDigit = "[0-9]";
To:
final String isDigit = "";
Output:
+
I can not force both numbers and characters to be stored in the queue. Only one or the other.
source
share