Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Basics Perfecting the Prototype Looping until the value passes

Claudiu Marcu
PLUS
Claudiu Marcu
Courses Plus Student 991 Points

What is wrong?

Why is not working?

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

response = console.readLine("Do you understand do while loops?  ");
boolean INValidWord;
do { 
    INValidWord = (response.equals("No"));
  if (INValidWord) {
  console.printf("Raspuns incorect...\n\n");}
} while (INValidWord);

2 Answers

Grigorij Schleifer
Grigorij Schleifer
10,363 Points

Hi Claudiu,

you don´t need to create a boolean variable. You can handle this challenge much easier :)

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 this helps

Grigorij