我编写了一个将中缀表达式转换为后缀表达式的程序。但是,我需要进行多个输入并在找到 0 时停止。
我所拥有的是,
输入:(3+4)*(3-1)
输出:4 + 3 1 - *
我需要的是,
输入:
(3+4)*(3-1)
(3*4)-(3*1)
(3+4)*(3-1)
(3+2)*((3-3)
(3+4)*(3-1)
0
输出:
4 + 3 1 - *
4 * 3 1 * -
4 + 3 1 - *
语法错误
4 + 3 1 - *
结尾
代码是:
public static void main(String args[])throws IOException
{
BufferedReader input = new BufferedReader (new InputStreamReader(System.in));
String s = input.readLine();
String pf = new String();
int i=0, check=0;
Stack<Character> s1 = new Stack<>();
while(i<s.length())
{
if(isOperand(s.charAt(i)))
{
pf += s.charAt(i);
}
else if(isOperator(s.charAt(i)))
{
while (!s1.empty() && s1.peek() != '(' && compareOperators(s1.peek(),s.charAt(i)) <= 0)
{
pf += ' ';
pf += s1.peek();
s1.pop();
}
pf += ' ';
s1.push(s.charAt(i));
}
else if (s.charAt(i) == '(')
{
s1.push(s.charAt(i));
}
else if (s.charAt(i) == ')')
{
check++;
while (!s1.empty())
{
if ((char)s1.peek() == '(')
{
check--;
s1.pop();
break;
}
pf += ' ';
pf += s1.peek();
s1.pop();
}
}
i++;
}
while (!s1.empty()) {
if(s1.peek()=='(')
check--;
pf += ' ';
pf += s1.peek();
pf += ' ';
s1.pop();
}
if(check!=0)
System.out.println("Syntax Error");
else
{
System.out.println(pf);
}
}
谁能帮我?