Pregunta

error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.String.charAt(Unknown Source) at Convert.main(Convert.java:16)

public class Convert {

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;

}
}

¿Fue útil?

Solución

This statement is causing the problem:

while( str.length() >= 1 )  

Change it to:

while(i<str.length()) 

Reason: The while condition that you used always remains true, if user enters 5 letter string, then str.length() is 5, so the while condition while(5>=1) is always true, so control goes inside the loop and with every iteration i increases from 0,1,2,3,4 then 5. When i is 5, the exception is thrown because the string only has 0,1,2,3,4 characters..

Edit:
Fixed the logic in operand method:

public static boolean operand(char b) {
    if (b == '+' || b == '-' || b == '*' || b == '/')
        return false;
    else
        return true;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top