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

mustafa attaie
mustafa attaie
8,068 Points

Not understanding Do while loops in java

I've watched the video a couple of times and i still feel like I'm not getting it. Could someone please explain to me why my code is wrong?

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?");

do {
 console.printf(response);
} while (response == "No");

4 Answers

You need to declare your "response" variable outside of the do while loop setting it equal to empty string (" "). Next you need to keep having the user input a response for it to test if the response is yes then the loop will end.

The way that you had it written you asked the user one time for a response and that value was stored; then it went into the loop with it and kept printing their one response while the loop kept checking for a different response, but would never find one- this here is what is called an infinite loop.

String response = "";

do{

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

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

 // finish your last line here...
mustafa attaie
mustafa attaie
8,068 Points

that answer won't pass for the first part of the task.

sorry add an extra ")" to the end of the while part.

while(response.equalsIgnoreCase("No"));

I just typed it up real fast and didn't run it, sorry about that.

Blake Larson
Blake Larson
13,014 Points

String response; boolean invalidResponse; do { response = console.readLine("Do you understand do while loops?"); invalidResponse = response.equalsIgnoreCase("No"); if (invalidResponse) { console.printf("That is not a valid response"); } } while (invalidResponse);

Declaring the String and boolean outside the do code block.