使用BlueJ编写代码和jUnit来测试它。Java Postfix字符串转换
试图转换infixToPostfix类我从我的实验室类中使用char使用字符串。这将使它不是被限制在char的单个输入“ab + cd * - ”中,它可以读取“ab + c - d * - ”
它正在处理堆栈,它是对我来说相当新鲜,我不知道我会如何去做这件事。我到目前为止的代码是:
public class InfixToPostfix
{
private Stack operators = new Stack();
/**
* Constructor for objects of class InfixToPostfix
*/
public InfixToPostfix()
{
}
/**
* toPostfix
*/
public String toPostfix(String infix)
{
String [] tokens = new String[100];
int i;
int length = infix.length();
String operator;
String output = "";
for (i = 0; i < length; i++)
{
if (isOperator(tokens[i]))
if (operators.empty())
// 2. If the stack is empty, push the incoming operator onto the stack.
operators.push(tokens[i] + " ");
else
{
if (operatorLessPrecedence(tokens[i]))
// 3. If the incoming symbol has equal or lower precedence than the
// symbol on the top of the stack, pop the stack and print the top
// operator. Then test the incoming operator against the new top of stack.
// Push the incoming symbol onto the stack.
{
do
{
output = output + operators.pop();
}
while (!operators.empty() && operatorLessPrecedence(tokens[i]));
operators.push(tokens[i] + " ");
}
else
// 4. If the incoming symbol has higher precedence than the top of the stack,
// push it on the stack.
operators.push(tokens[i]);
}
else
// 1. Print operands as they arrive.
output = output + tokens[i] + " ";
}
while (!operators.empty())
{
// 5. At the end of the expression, pop and print all operators on the stack.
operator = (String)operators.pop();
output = output + operator + " ";
}
return output;
}
/**
* isOperator
*/
public boolean isOperator(String c)
{
if( c.equals("/") ||
c.equals("'") ||
c.equals("+") ||
c.equals("-"))
return true;
else
return false;
}
/**
* operatorLessPrecedence
* Compare operator with top of stack
* Assume association left to right
*/
public boolean operatorLessPrecedence(String o)
{
int operatorPrecedence = precedence(o);
int tosPrecedence = precedence((String)operators.peek());
return (operatorPrecedence <= tosPrecedence);
}
/**
* precedence
*/
public int precedence(String o)
{
switch (o)
{
case "+": return 1;
case "-": return 1;
case "*": return 2;
case "/": return 2;
}
return 5;
}
}
所以,当我在使用的assertEquals JUnit测试;
@Test
public void testAddSub()
{
InfixToPostfix test = new InfixToPostfix();
assertEquals("1 2 +", test.toPostfix("1 + 2"));
assertEquals("2 1 -", test.toPostfix("2 - 1"));
}
我得到一个异常的方法目前,在我这是用于测试字符的什么,我认为是正确的,.equals()方法来测试字符串从“==”改变了isOperator方法,我会只能得到空输出..
我不想要一个直接的代码,或者我究竟做了什么错误,只是在正确的方向上“强有力”的推动,或者我可以看看。谢谢。