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
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.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started