測試程序:隊列不產生正確的輸出
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 = "";
輸出:
+
我不能讓這兩個數字和符號在隊列中存儲。只有一個或另一個。
固定它。謝謝。 – wildExploit