Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
String[] wordArray = {"wheels", "on", "the", "bus"};
RandomStringChooser sChooser = new RandomStringChooser(wordArray);
for (int k = 0; k < 6; k++) {
System.out.print(sChooser.getNext() + " ");
}
// Possible output
// bus the wheels on NONE NONE
RandomLetterChooser letterChooser = new RandomLetterChooser("cat");
for (int k=0; k<4; k++) {
System.out.print(letterChooser.getNext());
}
// Possible output
// actNONE
public class RandomLetterChooser extends RandomStringChooser {
public RandomLetterChooser( String str ) {
super( getSingleLetters( str ) );
}
public static String[] getSingleLetters( String str ) {
String[] out = new String[str.length()];
for (int i=0; i<str.length(); i++) {
out[i] = str.substring(i, i+1);
}
return out;
}
}
public class RandomLetterChooser extends RandomStringChooser {
public RandomLetterChooser(String str) {
// To be implemented in Part (B)
}
public static String[] getSingleLetters(String str) {
// Implementation not shown
}
}
import java.util.ArrayList;
public class RandomStringChooser {
private ArrayList<String> wordList;
public RandomStringChooser( String[] words ) {
wordList = new ArrayList<>();
for ( String word : words ) {
wordList.add( word );
}
}
public String getNext() {
if ( wordList.size() == 0 ) {
return "NONE";
}
int rnd = (int)(Math.random() * wordList.size());
return wordList.remove( rnd );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.