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

Task 2 of 3 Java Basics DO WHILE Loops Question.

So I was refreshing my knowledge on certain things when I decided to try a different route, I ran this code featured below and it said "Bummer! Your code took too long to run" I just wanted to find out why it says that? What about my code is wrong in the sense that its endlessly looping nothing and in so can't find a response???

I can complete this task another way, I just figured when I came across this I should ask why I came to this problem so that I could get a better understand of the code I'm writing.

I also came across one when using the == sign that said "Bummer! Try again!" which I assume means it doesn't want me using the == quite yet in these challenges.

Example.java
String response = console.readLine("Do you understand do while loops? ");
boolean wrongAnswer;
do {
  wrongAnswer = (response.equals("No"));
  if (wrongAnswer);

} while(wrongAnswer);

2 Answers

Dan Johnson
Dan Johnson
40,533 Points

An if statement on it's own won't do anything, it needs some code associated with its condition. You'll also need to prompt the user for a new value each time in the loop or you'll be stuck with the first response.

Here's an example using an if statement for breaking out of an otherwise infinite loop:

String response = console.readLine("Do you understand do while loops? ");
boolean wrongAnswer;
do {
  // Prompt the user each time
  response = console.readLine("Do you understand do while loops? ");
  wrongAnswer = (response.equals("No"));
  // If the answer isn't wrong
  if (!wrongAnswer) 
    //break out of the loop
    break;

// Using the if for termination so we'll just always have this condition be true
} while(true);

Thank you Dan, cleared it up well and truly for me :)