import java.util.Scanner;
public class GuessTheWord {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Player 1: Enter two magic words");
String mw1 = scan.next();
String mw2 = scan.next();
System.out.println("Player 2: Guess one of the words");
String guess = scan.next();
int guesses = 1;
boolean frootyLoops = (guess.equals(mw1) || guess.equals(mw2));
//this is good so far
while (! \frootyLoops) {
System.out.println("Nope");
System.out.println("Player 2: Guess one of the words");
guess = scan.next();
guesses++;
frootyLoops = (guesses > 5 || (guess.equals(mw1) || guess.equals(mw2)));
}
//end is fine, just fix the loopyfrooty
if (guesses > 5) {
System.out.println("Game over");
}
else {
System.out.println("YES! Guesses: " + guesses);
}
}
}
And, my code is working for every test case that it’s given, except for this one:
Is there anything different about this test case compared to the others?
Also, the error message is telling you that the exception is occurring on line 17 of your code. Look at that line to see what it is doing, and combine that with the answer to my question above and hopefully you will see why this is happening.
Another hint: Google “java NoSuchElementException” I think you will find it very illuminating.
The only thing different about this test case is that it forces the user to run out of guesses. And on line 17 my code just reassigns the guess value. And I looked up that kind of error and that still doesn’t help me.
Wait, I fixed it. My boolean condition for the guesses was one too high, and after I reduced it to 4 and added an extra print statement in the game over part of the if, it worked.
is that it was trying to pull the next value in from the input but there wasn’t a value because in this test case all of the guesses had been used. That is what the exception was telling you.
If you want to challenge yourself a little further, modify your function so it isn’t dependent on a set number of guesses. Right now the first line of your input is the two magic words and then you never have more than five lines of guesses after that. Modify your function so you don’t know how many guesses you’ll have after the two magic words. Could be 1, could be 10. Also, they may eventually get the right answer or they may never get the right answer.
Also, you should be able to reduce the redundancy here. Repeated code = code that will break in future updates because you forget to make some small change the exact same way between the two copies.