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

Java Java Basics Perfecting the Prototype Looping until the value passes

JAVA BASICS: Last Challenge - do while loops --

Ive been stuck for an hour trying to solve the 2nd part of the last challenge of Java Basics - do while loops - (cant imagine the third one)

So far im stuck with this piece of code

Challenge is to continually prompt do while loop with the response as "no". Any help will be greatly appreciated. Thanks.

Example.java
// I have initialized a java.io.Console for you. It is in a variable named console.

String response = console.readLine("Do you understand do while loops?  ");
boolean badAnswer;
do { 

  response = console.readLine("Do you understand do while loops?  ");
  badAnswer = (response.equalsIgnoreCase("no"));
} while (response.equalsIgnoreCase("yes"));

3 Answers

Allan Clark
Allan Clark
10,810 Points

Remember DRY (Don't Repeat Yourself). The two readLine calls are redundant, remember do-while loops execute whats inside the loop before checking if it should continue. So on the first execution you get input from the user, then over write that by getting input from the user again. The variable does still need to be declared outside the loop. (the boolean variable isn't really needed)

String response;

do {

       response = console.readLine("Do you understand do while loops?  ");

} while (response.equalsIgnoreCase("no"));

Thank you Allan!

I hate that now that I take a look at your code it seems so easy and logical and when I was trying to solve it by myself, it took me more than an hour and I couldnt even pass it :(

Anyway I will put extra focus and effort on the tips you talked about, specially DRY.

Allan Clark
Allan Clark
10,810 Points

Stick with it, keep coding and asking questions thats the only way to get better! :D

Ahmad Khaled
Ahmad Khaled
13,026 Points

I was stuck at this challenge like forever! :D I couldn't even understand the question!

THANKS :)