Advertisement
Guest User

Untitled

a guest
Oct 1st, 2014
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.ArrayList;
  3.  
  4. public class A2Q5
  5. {
  6.  
  7.     public interface Filter
  8.     {
  9.         boolean accept(Object x);
  10.     }
  11.    
  12.     // class ShortWordFilter implements a Filter class for filtering a list of strings by char count
  13.     public static class ShortWordFilter implements Filter
  14.     {
  15.        
  16.         private static final ArrayList<String> theList = new ArrayList<>();
  17.        
  18.         // ShortWordFilter constructor gets word from main and sends to filter method for further processing
  19.         public ShortWordFilter(Object word)
  20.         {
  21.             filter(word);
  22.         }
  23.        
  24.         // filter method determines if string is less than 5 char long and assigns it to an arraylist if it is
  25.         public void filter(Object word)
  26.         {
  27.             if (word.toString().length() < 5)
  28.             {
  29.                 theList.add((String) word);
  30.             }
  31.         }
  32.        
  33.         // collectAll gets list of objects and data from Filter interface and assigns for main
  34.         public static ArrayList<Object> collectAll(ArrayList<Object> objects, Filter f)
  35.         {
  36.             objects = new ArrayList<Object>(theList);
  37.             return objects;
  38.         }
  39.        
  40.     }
  41.    
  42.     // main method contains a loop asking for different words from the user
  43.     public static void main(String[] args)
  44.     {
  45.                
  46.         Scanner in = new Scanner(System.in);
  47.         String word = "";
  48.        
  49.         ArrayList<Filter> filterList = new ArrayList<Filter>();
  50.        
  51.         while (!word.equals("0")) {
  52.             System.out.println("Please input a word or '0' to end the loop:");
  53.             word = in.nextLine();
  54.             filterList.add(new ShortWordFilter(word) {});
  55.         }
  56.        
  57.     }
  58.        
  59.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement