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

Why won't my code run correctly?

I am doing the Java Basics final challenge. I have been getting errors like it was in a continuous loop and now I get the error that says my loop took too long. What am I doing wrong???????

Example.java
// I have initialized a java.io.Console for you. It is in a variable named console.
String question = console.readLine("Do you understand do while loops?");
String response = console.readLine("Enter your answer:  ");
Boolean isInvalidWord;
do {
  isInvalidWord = (response.equals("No"));
} while (isInvalidWord);

1 Answer

Hi Candice,

the problem here is simple. If a user enters "No" then the condition response.equals("No") is TRUE. So the variable isInvalidWord holds the value TRUE.

When your program enters the line below (while(isInvalidWord)) it basically reads while(TRUE), right? So the program will go back up to do and repeat checking if response.equals("No") which, again, will be TRUE.

The above will keep repeating indefinetly because if the user entered "No" once, the user has no way of changing their response (the variable isInvalidWord) inside the loop, and so that variable will be TRUE forever. This is why it's continuous.

To fix this, move the question down inside the loop. Like this:

// I have initialized a java.io.Console for you. It is in a variable named console.
String question = console.readLine("Do you understand do while loops?");
Boolean isInvalidWord;
String response;
do {
  response = console.readLine("Enter your answer:  ");
  isInvalidWord = (response.equals("No"));
} while (isInvalidWord);

This will allow the user to change their answer inside the loop. If they say "No", they will simply be prompted again until they say something different, at which stage isInvalidWord will be FALSE and the while-condition will fail and not jump up.

Hope that helps! :)

Thanks.