2016 FRQ question #1

a. Write the entire RandomStringChooser class. Your implementation must include an appropriate constructor and any necessary methods. Any instance variables must be private. The code segment in the example above should have the indicated behavior (that is, it must compile and produce a result like the possible output shown). Neither the constructor nor any of the methods should alter the parameter passed to the constructor, but your implementation may copy the contents of the array.

public class RandomStringChooser {   //makes class

    public RandomStringChooser(String str) { //creates class constructor for RandomStringChooser class
        ArrayList<String> stringArray = new ArrayList<String>(); 
        ArrayList<String> z = new ArrayList<String>(); 
    }

    public static void getNext(String[] args) { //getNext method
        for (int l = 0; l < 3; l++) { //running 3 times to show that it is random each time
            z.clear();
            stringArray.add("chicken");  //adding a couple inputs to the initial list
            stringArray.add("cow");  
            stringArray.add("pig");  
            int num = stringArray.size();
            for (int i = 0; i < 4; i++) { //for loop that iterates 4 times, which is one more than the amount of elements in the initial array
                int b = stringArray.size(); // sets b to the number of elements in the initial array
                int random = (int)(Math.random() * stringArray.size()); //randomizes a number
                if (b > 0) { //if the amount of elements in the initial array is greater than 0, first add the chosen element to a new array and then delete that element from the original array
                    z.add(stringArray.get(random));
                    stringArray.remove(random);
                }
                else { // if the amount of elements in the initial array is 0, then it adds none to the new array
                    z.add("None");
            
                }
            }
            System.out.print(z + " ");  //prints final array  
        }    
    }   
}   

RandomStringChooser.getNext(null);
[chicken, cow, pig, None] [chicken, pig, cow, None] [cow, chicken, pig, None] 

b. Complete the RandomLetterChooser constructor below. /** Constructs a random letter chooser using the given string str.

  • Precondition: str contains only letters. */ public RandomLetterChooser(String str)
public RandomLetterChooser(String str) //finish constructor and calls the superclass method getSingleLetters
{
    super(getSingleLetters(str));
}