Advertisement
Guest User

PassAnEnum

a guest
Sep 26th, 2011
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. import java.util.LinkedList;
  2.  
  3. public class PassAnEnum {
  4.     public static void main(String[] args) {
  5.         MagicGun gun = new MagicGun();
  6.         gun.loadWith(Ammo.PEBBLE);
  7.         gun.loadWith(Ammo.BULLET);
  8.         gun.loadWith(Ammo.MISSILE);
  9.         for(int i=0; i<5; i++){
  10.             try {
  11.                 Ammo shot = gun.shoot();
  12.                 System.out.printf("You've %s the target with a %s!\n", shot.getEffect(), shot.toString().toLowerCase());
  13.             } catch (GunIsEmptyException e) {
  14.                 System.err.printf("click\n");
  15.             }
  16.         }
  17.     }
  18. }
  19.  
  20. class MagicGun {
  21.     LinkedList<Ammo> ammos = new LinkedList<Ammo>();
  22.     public void loadWith(Ammo ammo){
  23.         ammos.add(ammo);
  24.     }
  25.     public Ammo shoot() throws GunIsEmptyException{
  26.         if (ammos.isEmpty()) {
  27.             throw new GunIsEmptyException();
  28.         }
  29.         return ammos.remove();
  30.     }
  31. }
  32.  
  33. class GunIsEmptyException extends Exception { }
  34.  
  35. enum Ammo {
  36.   PEBBLE("annoyed"), BULLET("holed"), MISSILE("obliterated");
  37.   private String effect;
  38.   private Ammo(String effect) {
  39.     this.effect = effect;
  40.   }
  41.   public String getEffect() {
  42.     return effect;
  43.   }
  44. }
  45.  
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement