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!

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


Java Hangman: how can I check for characters, or a null character? Hitting Enter before entering a char crashes it.

In the first example, the code throws an error if the character entered is not a letter. I'm trying to use a second if (or an OR/|| in the first clause) to make sure that just hitting enter without typing a character doesn't crash the program. Currently a "String index out of range: 0" error happens.

if (! Character.isLetter(letter)) {  
      throw new IllegalArgumentException("A letter is required");
      if (Character.getName(letter) == null)
      {  //Don't forget to validate for no chars entered!
      throw new IllegalArgumentException("A letter is required");

Seems like variable letter can be an alphanumeric character or a zero length string. Chars cannot be zero length but Strings can. I would make letter a String variable and then write the following code:

String letter;

//sample input #1
letter = "A";
//sample input #2
letter = "8";
//sample input #3
letter = "";

/*if only the first character of the input string contained in the variable letter is important,
you can convert the String into an array of chars with toCharArray() and reference the 
first element of that array with toCharArray()[0], which can then serve as the argument for
the static isLetter() method from the Character class

if (letter.length() == 0) {
   throw new IllegalArgumentException("A value is required.");
} else if (!Character.isLetter(letter.toCharArray()[0])) {
    throw new IllegalArgumentException("A letter is required.");
} else {
    System.out.println("Input value " + letter + " is a valid letter.");

Perhaps a while-loop would be useful in this case. You could keep asking for input until a valid letter is provided. No need to crash the program on them.