Java.lang.ArrayIndexOutOfBoundsException: -1

1 resposta
R

Olá a todos,

Estou a tentar fazer um programa que faça o cálculo de uma expressão na notação posfix.
mas estou com um problema. Tenho um erro quando executo que não estou a conseguir corrigir.
Quando na excução ponho 5 9 8 + 4 6 * * 7 + *, ele retorna uma excepção:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at PilhaArray.pop(PilhaArray.java:31)
at Postfix.CalculPostFix(Postfix.java:29)
at Postfix.main(Postfix.java:38)

Alguem me pode ajudar?

Aqui vai o meu código (que faz 3 ficheiros .java).

Obrigado.

//INTERFACE STACK
public interface Stack
{
     public void push(int i);
    public int pop();  
    public boolean isEmpty();
}
//CLASSE PILHAARRAY
public class PilhaArray implements Stack
{
    private int[] stack;
    private int n;
    
    public PilhaArray()
    {
        stack = new int[1000000];
        n=-1;
    }
    
    
    public boolean isEmpty()
    {
        return n == -1;
    }
    
    
    public void push(int item)
    {
        if (n < stack.length)
        {
            stack[++n] = item;
        }
    }
    

    public int pop() {
        
        int item = stack[n--];
        return item;
    }

}
//CLASSE POSTFIX
import java.io.*;

public class Postfix
{
    public static void CalculPostFix(String s2)
    {
        PilhaArray s = new PilhaArray ();  
        
        for (int i = 0; i < s2.length(); i += 2)
        {
            if (s2.charAt(i) == '+')
                s.push(s.pop() + s.pop());
            else if (s2.charAt(i) == '*')
                s.push(s.pop() * s.pop());
            else
            {
                int num = 0;
                do
                {
                    num = num*10 + s2.charAt(i)-'0'; // Constrói número
                    ++i;
                }
                while (s2.charAt(i) != ' ');
                --i;
                s.push(num);
            }
        }
        
        System.out.println(s.pop());
    }
    

      public static void main(String[] args) throws IOException
     {
      BufferedReader stdr = new BufferedReader(new InputStreamReader(System.in));
  
       String line = stdr.readLine();    
       CalculPostFix(line);
     }
}

1 Resposta

BrunoBastosPJ

Sua String line está vindo vazia, e você está tentando chamar o método pop antes de chamar o método push, por isso o valor do seu n está -1.

Criado 10 de maio de 2009
Ultima resposta 13 de mai. de 2009
Respostas 1
Participantes 2