import java.util.Scanner; public class WordGame { public static void main(String
ID: 3805919 • Letter: I
Question
import java.util.Scanner;
public class WordGame
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String playAgain = "YES";
while (playAgain.equalsIgnoreCase("YES"))
{
boolean won = playTheGame(keyboard);
if (won)
System.out.println("The word guesser won!");
else
System.out.println("The word guesser lost!");
System.out.println("Do you want to play again?");
playAgain = keyboard.nextLine();
}
}
public static boolean playTheGame(Scanner keyboard)
{
String word; // the word to be guessed
String guess=""; // the current guess, empty so the first
//iteration doesn't break
System.out.println("Enter a word for your opponent to guess");
word = keyboard.nextLine();
String shuffled = shuffle(word);
// Show the shuffled word one character at a time, allowing the
// user to guess
for(int index = 1; index<shuffled.length()+1
&& guess.equalsIgnoreCase(word)== false;++index)
{
// This shows one more character each time through
System.out.println("Some characters are: " +
shuffled.substring(0,index));
System.out.println("What is your guess?");
guess = keyboard.nextLine();
}
// If the guess is the word, the guesser won
return guess.equalsIgnoreCase(word);
}
public static String shuffle(String letters)
{
// StringBuilders are like Strings,except we can edit characters
StringBuilder result = new StringBuilder(letters);
// for each letter, swap it with a randomly chosen letter
for(int index = 0; index<result.length(); ++index)
{
// Find the random location--all parentheses are necessary
int rand = (int)(Math.random()*result.length());
// Find the letter at the next location
char c = result.charAt(index);
// Swap the letter at the random location with the next one
result.setCharAt(index, result.charAt(rand));
result.setCharAt(rand, c);
}
// Turn the StringBuidler back into a String object
return result.toString();
}
}
1) In the program above, give the order in which the three static methods (main, shuffle, playTheGame) are executed if the user input is:
dog
dude
dug
good
yes
omega
and
aorta
agog
omega
no
Explanation / Answer
The order in which the static methods are called are ->
1. main
2. playTheGame
3. shuffle
4. playTheGame
5. playTheGame
6. playTheGame
7. main
8. playTheGame
9. shuffle
10. playTheGame
11. playTheGame
12. playTheGame
13. playTheGame
14. main.
You can trace the execution by understanding the program flow.
OR
If you do not know the program flow, the you can trace the flow by seeing the output statements.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.