队列没有产生正确的输出
queue not producing correct output
测试程序:
public class Test
{
public static void main(String[] args)
{
String str = "1 + 4";
new MyClass(str);
}
}
问题代码:
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());
}
}
输出:
14
输出应该是:
14+
如果我改变:
final String isDigit = "[0-9]";
收件人:
final String isDigit = "";
输出:
+
我无法将数字和符号都存储在队列中。只有一个。
您的问题在于在 for 循环中使用“.size()”来确定输出中的元素数量。因为调用 poll() 的循环的每次迭代都会从输出中删除一个元素,所以循环提前退出。
要解决此问题,请在 运行 循环之前将大小存储在单独的变量中。
像这样:
int size = output.size();
for (int j = 0; j < size; j++)
{
postFixStr.append(output.poll());
}
你的问题实际上是 for
循环控制。
替换为:
for (int j = 0; j < output.size(); j++)
{
postFixStr.append(output.poll());
}
为此:
while (output.size() > 0)
{
postFixStr.append(output.poll());
}
它会非常有效。
说明
因为表达式 j < output.size()
在每次迭代之前被评估,并且 output
列表在每次循环迭代 2 次而不是预期的 3 次时删除一个元素。
测试程序:
public class Test
{
public static void main(String[] args)
{
String str = "1 + 4";
new MyClass(str);
}
}
问题代码:
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());
}
}
输出:
14
输出应该是:
14+
如果我改变:
final String isDigit = "[0-9]";
收件人:
final String isDigit = "";
输出:
+
我无法将数字和符号都存储在队列中。只有一个。
您的问题在于在 for 循环中使用“.size()”来确定输出中的元素数量。因为调用 poll() 的循环的每次迭代都会从输出中删除一个元素,所以循环提前退出。
要解决此问题,请在 运行 循环之前将大小存储在单独的变量中。
像这样:
int size = output.size();
for (int j = 0; j < size; j++)
{
postFixStr.append(output.poll());
}
你的问题实际上是 for
循环控制。
替换为:
for (int j = 0; j < output.size(); j++)
{
postFixStr.append(output.poll());
}
为此:
while (output.size() > 0)
{
postFixStr.append(output.poll());
}
它会非常有效。
说明
因为表达式 j < output.size()
在每次迭代之前被评估,并且 output
列表在每次循环迭代 2 次而不是预期的 3 次时删除一个元素。