Olá a todos,
Estou a precisar da vossa preciosa ajuda…
Trata-se de um programa que recebe uma expressão em postfix e retorna o resultado (ou deveria retornar…)
Quando na execuçã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:
at Postfix.CalculPostFix(Postfix.java:
at Postfix.main(Postfix.java:
De onde vem o problema? :roll:
Aqui vai o meu código:
[code]
//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);  
  }  
}[/code]
//INTERFACE STACK
public interface Stack
{
     public void push(int i);
    public int pop();  
    public boolean isEmpty();
}
[code]
//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;
}
}[/code]
Obrigado.
