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 trialDaniel Hernandez-Zuleta
1,478 PointsWhy do we use char guess = guessAsString.charAt(0) in the prompting for guesses video?
thank you.
1 Answer
Allan Clark
10,810 PointsIn order to get the guess from the user you have to call the readLine() method on the console. http://docs.oracle.com/javase/7/docs/api/java/io/Console.html
This method takes in the whole line from the user (not just the first letter of the line) and returns it as a String. Since we are only concerned with one letter of what the user input, keeping this data stored in a String variable is not efficient. We want the variable to act as a stand alone letter (aka char) rather than a word (aka String). The charAt() method on Strings takes the index you are looking for and returns the charAt that index. Strings are 0 indexed so charAt(0) will return the first char of any String. http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
*Note: we want the user input to be only one letter but we do not know what Joe Schmoe will input so we have to programmatically change the input to what we want.
String guessAsString = console.readLine("Enter a letter: ");
// gets the input from the user and stores as a String so
// guessAsString for example could be "eat my shorts"
char guess = guessAsString.charAt(0);
// gets the first letter of the String and stores it as a char
// now guess is set to 'e'
This becomes helpful later when you have to use logical operators to check that guess against chars in the key word (or whatever they call the word that is trying to be guessed haha).