Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Adrian Nacor
740 PointsAccessing a variable inside the loop, from outside.
I'm using Eclipse to do the "Hangman task", whenever I run the program....
public boolean promptForGuess()
{
Scanner keyboard = new Scanner(System.in);
boolean isHit = false;
boolean isValidGuess = false;
while (! isValidGuess)
{
System.out.println("Enter a letter: ");
String guessAsString = keyboard.next();
char guess = guessAsString.charAt(0);
}
try
{
isHit = mGame.applyGuess(guess);
isValidGuess = true;
}
catch (IllegalArgumentException iae)
{
System.out.printf("%s. Please try again.\n", iae.getMessage());
}
return isHit;
}
I get this error...
You have Exception in thread "main" 7 tries left to solve: --------- java.lang.Error: Unresolved compilation problem: guess cannot be resolved to a variable
at Prompter.promptForGuess(Prompter.java:39) at Prompter.play(Prompter.java:17) at Hangman.main(Hangman.java:10)
1 Answer
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsTry to put declaration of char guess; outside of the loop. should work...:
char guess;
while (! isValidGuess) {
System.out.println("Enter a letter: ");
String guessAsString = keyboard.next();
guess = guessAsString.charAt(0);
}
// here guess will be available