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

Chigozie Ofodike
Chigozie Ofodike
11,197 Points

How do I stop this infinite loop?

I think my program is running infinitely, is it? If so why is it? And how i stop it?

Example.java
// I have initialized a java.io.Console for you. It is in a variable named console.
String response;
boolean answerYes;
do{
  response = console.readLine("Do you understand do while loops?  \n");
  answerYes = (response.equalsIgnoreCase("no"));
}while(response.equals(answerYes));

1 Answer

Yes, your code runs in a infinite loop. This is because you are comparing a String response with a boolean answerYes.

The equalsIgnoreCase() returns type boolean. You used this correctly when assigning the value to answerYes here:

answerYes = (response.equalsIgnoreCase("no"));

However here:

while(response.equals(answerYes)); 

is where you compare the string response with answerYes.

Because answerYes is a boolean you can use it as the condition for the do-while loop like this:

String response;
boolean answerNo; //change to answerNo for better readability of code
do{
  response = console.readLine("Do you understand do while loops?  \n");
  //answerNo equals true if the response equals "no", it equals false other wise  
  answerNo = (response.equalsIgnoreCase("no")); 
}while(answerNo); // while answer is true keep running the code