Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the first version of GladLibs we saw in this lesson, which stores label

ID: 3723616 • Letter: C

Question

Consider the first version of GladLibs we saw in this lesson, which stores label substitutions in ArrayLists. Assume an ArrayList named wordsUsed will keep track of words used as replacements so no replacement word will be used more than once. The code below was used as part of a program by a learner in the method processWord. The learner's program runs but still results in duplicate words sometimes.

String sub = getSubstitute(w.substring(first+1,last));
while (true) {
    if (wordsUsed.contains(sub)) {
        sub = getSubstitute(w.substring(first+1,last));
        break;
    }
    else {
        wordsUsed.add(sub);
    }
}

Which one of the following best explains why this code still returns duplicates sometimes?

Repeated words are also put into wordsUsed, so the call to getSubstitute may choose a repeated word.

If a word is a repeated word, then this code gets another random word and uses that second word without checking to see if it is a repeated word.

The “if condition” is always false in the loop, so the else part is always executed. This always results in a second random word.

The “if condition” is always false the first time in the loop, so the else part is executed the first time through the loop. This means the while loop always executes its body at least twice so some words may be used a second time.

Explanation / Answer

You have not provided the code for getSubstitute() but I guess this method must be returning a random String from some list.

In the method processWord() :

In the code given above you are finding a random string with the help of getSubstitute() method ( In Variable sub) and then there is a check if the "wordsUsed" contains "sub" or not . In case that it is false there is no problem but if it is true again a random string is generated from getSubstitute() which can be same as the first time or completely new string But this new "sub" is never added to the "wordsUsed" list . So this can lead to duplicates.

I hope it solves your doubt.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote