我被困在此任务上。我正在阅读文件,每行我正在运行checkInfix静态方法。执行CheckInFix方法后,它应该返回我正在阅读的Infix行的计算。例如,第一个是5*6 4 = 34。如果没有,则应说"无效"。但是,如您所见,对于某些行,此程序的输出是错误的。我的输出在下面....
5 * 6 4< =这是正确的,因为它打印了34。
= 34
3-2 < =正确答案
无效
(3 * 4 - (2 5)) * 4/2< = =该版本应该打印10,用于答案,但不为prints。
无效
在无效
2 *(12 (3 5) * 2< =这是正确的
无效
无效
非常感谢您研究它!!!Code ::::>我没有发布主要功能,因为其中没有任何功能。如果您愿意,如果您想看到它,我可以发布它。
public static int checkInfix(String inf)
{
char[] c = inf.toCharArray();
Stack<Integer> into = new Stack<Integer>();
Stack<Character>charo = new Stack<Character>();
for (int i = 0; i < c.length; i++)
{
if (c[i] == ' ' || c[i]==',')
continue;
if (iOperand(c[i])){ // checking for operand 0 to 9
StringBuffer z = new StringBuffer();
while (i < c.length && c[i] >= '0' && c[i] <= '9')
z.append(c[i++]);
into.push(Integer.parseInt(z.toString()));
}
else if (c[i] == '(')
charo.push(c[i]);
else if (c[i] == ')')
{
while (!charo.empty()&& charo.peek() != '(')
into.push(calucator(charo.pop(), into.pop(), into.pop()));
charo.pop();
}
else if (iOperator(c[i])){ // checking for operator +,-,*,/
while (!charo.empty() && HigerPreced(c[i],charo.peek()))
into.push(calucator(charo.pop(), into.pop(), into.pop()));
charo.push(c[i]);
}
}//end of for loop
while (!charo.empty())
into.push(calucator(charo.pop(), into.pop(), into.pop()));
return into.pop();
}//end of checkinfix class
public static boolean iOperator(char C) {
if (C == '+' || C == '-' || C == '*' || C == '/' || C == '%' )
return true;
return false;
}
public static boolean iOperand(char C){
if (C >= '0' && C<='9')
return true;
return false;
}
//check for precedence
public static boolean HigerPreced(char oprt1,char oprt2){
if (oprt2 == ')' || oprt2 == '(' )return false;
if ((oprt1 == '*'|| oprt1=='/')&&(oprt1=='+'||oprt1=='-'))return false;
else
return true;
}
//calculating
public static int calucator(char into, int oprnd1, int oprnd2)
{
switch(into)
{
case '+': return oprnd1 + oprnd2;
case '-': return oprnd1 - oprnd2;
case '*': return oprnd1 * oprnd2;
case '/': return oprnd1/oprnd2;
}
return 0;
}
(oprt1 == '*'|| oprt1=='/')&&(oprt1=='+'||oprt1=='-')
oprt2
应该出现在此表达式中...目前永远不可能是真实的。