RandomStringChooser - Part A Parsons

Question 1. This question involves the implementation and extension of a RandomStringChooser class.

Part a. A RandomStringChooser object is constructed from an array of non-null String values. When the object is first constructed, all of the strings are considered available. The RandomStringChooser class has a getNext method, which has the following behavior. A call to getNext returns a randomly chosen string from the available strings in the object. Once a particular string has been returned from a call to getNext, it is no longer available to be returned from subsequent calls to getNext. If no strings are available to be returned, getNext returns "NONE.

The following code segment shows an example of the behavior of RandomStringChooser.

String[] wordArray = {"wheels", "on", "the", "bus"};
RandomStringChooser sChooser = new RandomStringChooser(wordArray);
for (int k = 0; k < 6; k++)
{
   System.out.println(sChooser.getNext() + " ");
}

One possible output is shown below. Because sChooser has only four strings, the string "NONE is printed twice.

bus the wheels on NONE NONE

There are many ways to write the code for the RandomStringChooser class. The mixed up code practice below is one way to solve it.

Mixed Up Code Practice

The mixed up code below includes the correct code for the class, a field, a constructor, and the <code>getNext</code> method. In the constructor it will create an <code>ArrayList</code> and fill it by looping through the array and adding each string to the list. In the <code>getNext</code> method, if the list length is greater than zero, it will pick a position at random in the list and remove the item from that position and return it. Otherwise, if the list is empty, it returns “NONE”. The blocks have been mixed up and include extra blocks that aren’t needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the <i>Check Me</i> button to check your solution.</p>

The mixed up code below uses a different algorithm to solve the same problem.

More Mixed Up Code Practice

The mixed up code below includes the correct code for the class, a field, a constructor, and the <code>getNext</code> method. In the constructor it will create an <code>ArrayList</code> and fill it by looping through the array and adding each string to the list. In <code>getNext</code> it will return “NONE” if the length of the list is 0. Otherwise, it will calculate a random index in the list, remove the string at that index, and return it. The blocks have been mixed up and include extra blocks that aren’t needed in the solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the <i>Check Me</i> button to check your solution.</p>

You have attempted of activities on this page