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

Kevin Jervis
Kevin Jervis
2,600 Points

Do While Loops

Hi guys. I'm a little stuck.Think I'm about 80% there :o(

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 loops?");
do {
  response = console.readLine("Do you understand loops?");
  if (response.equals("No");
  console.readLine("Do you understand loops?");
      }

2 Answers

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,252 Points

Hi Kevin,

you're making a good start but there's a few issues I can see. First, you don't need to use an if statement or prompt the user a third time.

// I have initialized a java.io.Console for you. It is in a variable named console.
String response = console.readLine("Do you understand loops?");

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

You want to keep prompting as long as the answer from the user is "No". You can do the condition you'd otherwise write in an if statement after the while keyword.

I'll leave you with the last part of the challenge! :)

Hi Jonathan,

Your code will prompt the user twice at the initial loop and comparing strings with == isn't best practice; .equals() is the preferred way, as the OP had done.

:wink: :+1:

Steve.

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,252 Points

equals didn't pass the code challenge when I tested it. That's what I expected, so the only other method is ==` which passed the challenge. Odd.

Must've just been having a 'moment' - working fine now. Hey ho - not a problem.

Kevin Jervis
Kevin Jervis
2,600 Points

That's awesome. I though I over complicated things. That's brilliant. Thanks Jonathan :o)

Hi Kevin,

You're pretty much there. Try something like this:

String response;

do{
  response = console.readLine("Do you understand loops?");
}while(response.equals("No")); // like what's in your if brackets

Make sense?

Steve.

Kevin Jervis
Kevin Jervis
2,600 Points

Thanks for breaking that down for me Steve. Makes sense now. I appreciate the help :o)