Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects (Retired) Creating the MVP Prompting for Guesses

Guilherme Rocha
Guilherme Rocha
934 Points

I 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
Jesse Devaney
6,632 Points

In 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. }