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

Robert Peterman
Robert Peterman
599 Points

Stuck on Do While loops excercise

The exercise wants me to do a "do while loop" as long as someone answers no on a yes or no question. I've been trying forever to get it figured out but am completely lost. Any help is appreciated.

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? no");
boolean answeredNo;
do {
  answeredNo = (response.equalsIgnoreCase(no));
  if (answeredNo){
    console.printf(response);
  }}
  while (answeredNo);

1 Answer

Teja Tummalapalli
Teja Tummalapalli
5,592 Points

Robert Peterman , Nice Try. Understanding do while may be more difficult than while. So let my try to explain.

You have solved the challenge 1 , congrats String response = console.readLine("Do you understand do while loops?"); ( Removed no form your statement). So this statement prompts the provided question and the response provided by the user is stored in the variable response. Notice that the variable response is the String.

If the response is No , you need to prompt the same question again. You need to continue this until the response is not equal to No. So how to do it. There need to be some kind of loop involved...generally it can be a do loop or and do while loop.

So how do we use do here

String response = console.readLine("Do you understand do while loops?");
while(response.equals("No")) {
  response = console.readLine("Do you understand do while loops?");
};

On first line , the repose is recorded. On Second line , while loop checks if the provided response is No. It it is equal to No while loop is executed...No again the response is recorded..And now goes back to while condition and check if the response entered second time is No. So this repeats until the response is not equal to No.

Similarly do while loop can be used here too..

String response = console.readLine("Do you understand do while loops?");
do {
  response = console.readLine("Do you understand do while loops?");
}while(response.equals("No"));

Pls comment if you don't understand any part..