Advertisement
apez1

Term 2: Lesson 14 - Coding Activity

Mar 6th, 2019
624
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. package random;
  2.  
  3.  
  4. import java.io.*;
  5. import java.util.*;
  6.  
  7.  
  8. class Main
  9. {
  10.  
  11.     /*
  12.      * Returns the number of Strings in the input list that start with the given
  13.      * letter. Implementation should use linear search, and ignore the case of
  14.      * the input letter.
  15.      */
  16.     public static int countLetter(ArrayList<String> list, String letter)
  17.     {
  18.        
  19.         int counter = 0;
  20.        
  21.         for(int i = 0 ; i < list.size(); i ++) {
  22.            
  23.             String first = list.get(i).substring(0, 1);
  24.            
  25.             if(first.equalsIgnoreCase(letter)) {
  26.                
  27.                 counter ++;
  28.                
  29.             }
  30.        
  31.         }
  32.    
  33.        
  34.         return counter ;
  35.    
  36.    
  37.     }
  38.  
  39.     public static void main(String str[]) throws IOException
  40.     {
  41.         /*
  42.          * Initialize an ArrayList of animals called zoo.
  43.          */
  44.         ArrayList<String> zoo = new ArrayList<String>();
  45.         zoo.add("Zebra");
  46.         zoo.add("Aardvark");
  47.         zoo.add("Emu");
  48.         zoo.add("Hippo");
  49.         zoo.add("Aligator");
  50.         zoo.add("Lion");
  51.         zoo.add("Giraffe");
  52.         zoo.add("Seal");
  53.         zoo.add("Tiger");
  54.         zoo.add("Elephant");
  55.  
  56.         /*
  57.          * Print the contents of the zoo.
  58.          */
  59.         System.out.println(zoo);
  60.  
  61.         /*
  62.          * Print the output from calling countLetter with various letters. For
  63.          * example, countLetter (zoo, "e") should return 2 while
  64.          * countLetter(zoo, "W") should return 0.
  65.          */
  66.         System.out.println("A: " + countLetter(zoo, "A"));
  67.         System.out.println("B: " + countLetter(zoo, "B"));
  68.         System.out.println("C: " + countLetter(zoo, "C"));
  69.         System.out.println("L: " + countLetter(zoo, "L"));
  70.         System.out.println("T: " + countLetter(zoo, "T"));
  71.  
  72.         System.out.println("a: " + countLetter(zoo, "a"));
  73.         System.out.println("b: " + countLetter(zoo, "b"));
  74.         System.out.println("c: " + countLetter(zoo, "c"));
  75.         System.out.println("l: " + countLetter(zoo, "l"));
  76.         System.out.println("t: " + countLetter(zoo, "t"));
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement