Advertisement
jtentor

Pila con excepciones para Marcos Gabriel Chosco

Sep 12th, 2017
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. package TP2;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class Pila {
  6.  
  7.     private ArrayList<Object> lifo = new ArrayList();
  8.  
  9.     public void Push(Object o) { // agrega valores a la pila
  10.         lifo.add(o);
  11.  
  12.     }
  13.  
  14.     public Object Pop() { // elimina o saca un elemento de la pila
  15.         if (!(lifo.isEmpty())) {
  16.             Object o = lifo.get(lifo.size() - 1); // el tamaño del array list para que empieze en 0 al agregar una valor
  17.             lifo.remove(lifo.size() - 1);
  18.             return o;
  19.         } else {
  20.             throw new RuntimeException("La pila esta vacia");
  21.         }
  22.     }
  23.  
  24.     public Object Peek() {
  25.  
  26.         if (!(lifo.isEmpty())) {
  27.             return lifo.get(lifo.size() - 1);
  28.         } else {
  29.             throw new RuntimeException("La pila esta vacia");
  30.         }
  31.     }
  32.  
  33.     public boolean Empty() {
  34.         return lifo.isEmpty();
  35.     }
  36.  
  37. }
  38.  
  39. // HASTA AQUI ES EL CÓDIGO DE LA CLASE PILA
  40.  
  41. package TP2;
  42.  
  43. public class MainPila {
  44.  
  45.     public static void main(String[] args) {
  46.         System.out.println("Pila: ");
  47.         Pila miPila = new Pila();
  48.        
  49.         miPila.Push("a");
  50.         miPila.Push("b");
  51.         miPila.Push("c");
  52.         miPila.Push("d");
  53.         miPila.Push("e");
  54.        
  55.         while(!miPila.Empty()) {
  56.             System.out.println(miPila.Pop());
  57.            
  58.         }
  59.         // para provocar el error descomentar la siguiente línea
  60.         // System.out.println("La pila esta vacia...." + miPila.Peek());
  61.        
  62.         // porción de código que atrapa la excepción disparada en el código de Pila
  63.         try {
  64.             System.out.println("La pila esta vacia...." + miPila.Peek());
  65.         } catch (Exception e) {
  66.             System.out.println("TONTO RETONTO, no se puede sacar algo de una pila vacía");
  67.         }
  68.        
  69.     }
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement