【发布时间】:2015-10-19 02:57:10
【问题描述】:
使用 BlueJ 编写代码并使用 jUnit 进行测试。
尝试将实验室课程中的 infixToPostfix 类从使用 char 转换为使用字符串。这将使它不再局限于单个输入,比如 char 的“ab+c-d*-”,而是能够读取“a b + 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;
}
}
所以当我在 jUnit 中使用 assertEquals 进行测试时;
@Test
public void testAddSub()
{
InfixToPostfix test = new InfixToPostfix();
assertEquals("1 2 +", test.toPostfix("1 + 2"));
assertEquals("2 1 -", test.toPostfix("2 - 1"));
}
我目前得到一个异常方法,在我将 isOperator 方法从用于测试字符的“==”更改为我认为正确的方法之前,使用 .equals() 方法测试字符串,我只会得到空输出..
我不想要一个直截了当的代码或我到底做错了什么,只是朝着正确的方向“有力”推动或我可以调查的事情。谢谢。
【问题讨论】: