Java 中缀码输出不正确
我被这项任务困住了。我正在读取文件,每行都运行checkInfix静态方法。在执行checkInfix方法之后,它应该返回我正在读取的中缀行的计算结果。例如,第一个是5*6+4=34。如果没有,那么应该说“无效”。但是,正如您所看到的,对于某些行,此程序的输出是错误的。 我的输出如下Java 中缀码输出不正确,java,Java,我被这项任务困住了。我正在读取文件,每行都运行checkInfix静态方法。在执行checkInfix方法之后,它应该返回我正在读取的中缀行的计算结果。例如,第一个是5*6+4=34。如果没有,那么应该说“无效”。但是,正如您所看到的,对于某些行,此程序的输出是错误的。 我的输出如下 5*6+4 oprt2应出现在此表达式中。。。目前它永远不会是真的。2*(12+(3+5)*2否,因为它缺少需要关闭的第一个开口支架 public static int checkInfix(String inf
5*6+4
oprt2
应出现在此表达式中。。。目前它永远不会是真的。2*(12+(3+5)*2否,因为它缺少需要关闭的第一个开口支架
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=='-')