A queue that does not produce the correct output

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.

+4
source share
2 answers

Your problem is loop control for.

Replace this:

for (int j = 0; j < output.size(); j++)
{
    postFixStr.append(output.poll());
}

for this:

while (output.size() > 0)
{
    postFixStr.append(output.poll());
}

and it will work like a charm.

Explanation

How an expression j < output.size()is evaluated before each iteration, and in the list, outputone element is deleted each time the loop repeats 2 times, and not 3, as expected.

+3
source

".size()" for . poll(), .

, .

:

int size = output.size();
for (int j = 0; j < size; j++)
{
  postFixStr.append(output.poll());
}
+1

Source: https://habr.com/ru/post/1612509/


All Articles