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 trialGuilherme Rocha
934 PointsI have a IOExeception
I'm trying to code this hangman code with Netbeans 8, but It's returning the following error: error: unreported exception IOException; must be caught or declared to be thrown String guessAsString = reader.readLine();
I'm using BufferedReader and InputStreamReader as Craig posted for another question, but don't works.
import java.io.BufferedReader; import java.io.InputStreamReader;
public class Prompter { private Game mGame;
public Prompter (Game game) {
mGame = game;
}
public boolean promptForGuess() {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(inputStreamReader);
System.out.print("Enter a letter: ");
String guessAsString = reader.readLine();
char guess = guessAsString.charAt(0);
return mGame.applyGuess(guess);
}
}
1 Answer
Jesse Devaney
6,632 PointsIn case the user doesn't enter a string, you have to be able to handle that exception.
first import the IOException class at the top of you class like so, import java.io.*;
You can use a try catch statement now to test to see if an exception is thrown and to handle it accordingly, try { InputStreamReader inputStreamReader = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(inputStreamReader); System.out.print("Enter a letter: "); String guessAsString = reader.readLine(); char guess = guessAsString.charAt(0); return mGame.applyGuess(guess); } catch(IOException e) { System.out.println("Your input was invalid"); return promptForGuess(); //Do this to recall the method so they can be prompted again. }