輸出不正確我堅持這個任務。我正在閱讀文件,並且每行都運行checkInfix靜態方法。執行checkInfix方法後,它應該返回我正在閱讀的中綴線的計算。例如,第一個是5 * 6 + 4 = 34。如果不是,那麼它應該說「無效」。但是,對於某些行,該程序的輸出錯誤,如您所見。 我的輸出低於....與綴代碼
5 * 6 + 4 = <因爲它打印這是正確34.
= 34
3 - 2 + < =正確答案
無效
(3 * 4 - (2 + 5))* 4/2 = <這一個應進行打印,10的答案,但犯規..pri NTS無效
無效
10 + 6 * 11 - (3 * 2 + 14)/ 2 = <這應該打印,答案66但犯規..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;
}
2 *(12 +(3 + 5)* 2 <=這是正確的,你不覺得有一個大括號丟失嗎?(第一想法) – VinayVeluri
否,因爲它缺少第一個需要關閉的開放括號 – calo