1
错误: 异常在线程 “主” java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:5 在java.lang.String.charAt(未知来源) 在Convert.main(Convert.java:16)这个错误和我的代码之间有什么错?
公共类转换{
public static void main(String[] args) {
int i=0;
int j=0;
char p[] = new char[10]; // postfix
Stk s = new Stk(); // stack
String str = new String(); // infix
str = JOptionPane.showInputDialog("Please enter a infix expression:");
while(str.length() >= 1)
{
if(operand (str.charAt(i)))
p[j++] = str.charAt(i);
else if (!operand(str.charAt(i)))
{
while(!s.isEmpty() && precedence(str.charAt(i)) <= precedence(s.stack[s.top]))
p[j++] = s.pop();
s.push(str.charAt(i));
}
i++;
}
while (!s.isEmpty())
{
p[j++] = s.pop();
}
String P = new String(p);
JOptionPane.showMessageDialog(null , "Postfix expression is : " + P);
}
public static boolean operand(char b)
{
if (b!='+' || b!='-' || b!='*' || b!='/')
return true;
else
return false;
}
public static int precedence(char c)
{
int x=0;
switch(c)
{
case '*':
case '/':
x=2;
break;
case '+':
case '-':
x=1;
break;
}
return x;
}
}
错误已更正,但输出错误!例如,当我输入“a + b * c”时,我会收到相同的字符串“a + b * c”,并且它会将表达式从中缀转换为后缀!请帮助我.. – endorbor
编辑了答案,问题出在你的'operand'方法中。 –
非常感谢您的帮助...... – endorbor