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

I can't figure this out for the life of me... Am I close?

Title... Sigh

Example.java
// I have initialized a java.io.Console for you. It is in a variable named console.
String response = "Yes";
String response;

do {
response = console.readLine("Do you understand do while loops?");
if(response.equalsIgnoreCase("no")){
console.printf("Try again");
  }
}while

3 Answers

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Jason,

the do while loop is pretty handy. The statement inside the do-part will be executed at least once. So you can ask the user for input and so on. You should understand that until the consition inside the while parenthesis is true, the do part will be executed.

The loop stops if the condition is false.

So how to write the do-while loop:

do {
//here goes your code that should be executed at least once
} while (condition); 
// while the condition is true, repeat the do-part of the loop
// if the condition is false, leave the loop and execute the code below

So the challenge can look like this:

String response;
do {
  response = console.readLine("Do you understand do while loops?");
} while (response.equalsIgnoreCase("No"));
// if you say "No", the condition is true and loop goes into do part again
//if you say Yes, the condition is false and the loop is over

console.printf("Because you said %s, you passed the test!", response);
// this line will only be executed if the loop is over - condition of while loop is false

Hope it helps

Grigorij

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,736 Points

You're declaring the response variable twice, just do it once. Also you need to put the condition after the keyword while, not within the curly braces.

String response;

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

Thanks!

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

You are very welcome,

could you mark an answer as best, so other Java-Ninjas could see this.

Greg