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
Joshua Wong
Courses Plus Student 572 Pointswhile loop does not automatically allow user to input new noun
I've been working through the "dork" and "jerk" use case in the "Censoring Words - Looping Until Value Passes" video in my own workspace. In the video, when "dork" or "jerk" are passed through the noun String, two actions occur: 1) the rejection String is printed, and 2) the "Enter a noun: " command automatically pops up to give the user a second chance. In my code, the first happens, but the second does not. Rather, I am given a blank line instead of the "Enter a noun: " command. I have to type something (any gibberish really) in order for the command to appear again, rather than the command automatically popping up as seen in the video. What happened? It seems like I have to type something to initiate the while loop? Here is my code:
String noun;
do {
noun = console.readLine("Enter a noun: ");
if (noun.equalsIgnoreCase("dork") ||
noun.equalsIgnoreCase("jerk")) {
console.readLine("Sorry, this noun is unacceptable. Please try again. \n\n");
}
} while (noun.equalsIgnoreCase("dork") || noun.equalsIgnoreCase("jerk"));
Thank you!
Edit: My code text for some reason will not recognize 'Enter' commands and is writing the code in one line. Not sure why that is the case, and it seems like I cannot screenshot the code to show. Sorry about that.
1 Answer
Stone Preston
42,016 Pointsthe reason this is happening is because you are using the readLine method.
console.readLine("Sorry, this noun is unacceptable. Please try again. \n\n");
Its expecting user input which is why you have to type something in to get the loop to continue.
You need to use printf instead:
do {
noun = console.readLine("Enter a noun: ");
if (noun.equalsIgnoreCase("dork") ||
noun.equalsIgnoreCase("jerk")) {
console.printf("Sorry, this noun is unacceptable. Please try again. \n");
}
} while (noun.equalsIgnoreCase("dork") || noun.equalsIgnoreCase("jerk"));
Joshua Wong
Courses Plus Student 572 PointsJoshua Wong
Courses Plus Student 572 PointsProblem solved after trying it out. Thanks!