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 trialLandon Johnson
Java Web Development Techdegree Student 391 PointsThere is nothing wrong with this code. i swear but its telling me error
a simple do while loop. help me plz
// I have initialized a java.io.Console for you. It is in a variable named console.
String response;
boolean wrong;
do {
response = console.readLine("Do you understand do while loops?");
wrong = response.equals("no");
if (wrong) {
console.printf("sorry try again"); }
}while(response.equalsIgnoreCase("no");
1 Answer
Yanuar Prakoso
15,196 PointsHi Landon Johnson You only need to write your code as I shown you below:
// I have initialized a java.io.Console for you. It is in a variable named console.
String response;
do {
response = console.readLine("Do you understand do while loops?");
} while(response.equalsIgnoreCase("no"));
you do not need the boolean:
wrong = response.equals("no");
to test the do while loop because the while part of the loop has done it for you. When I reviewed the challenge it does not require us to add another comment when the user answer no. Thus it will not necessary to do the if test using boolean wrong variable. But if you insist of doing so the main mistakes on your source code is you did not put another ')' in the end of while statement:
}while(response.equalsIgnoreCase("no");
it should be:
}while(response.equalsIgnoreCase("no"));
And if I may suggest you still do not need to use another boolean variable wrong since response.equals("no") will return boolean value needed by the if statement. For efficiency sake it does not need to add another variable since it was not repeatedly used anywhere else in the code. I propose this source code for your review:
// I have initialized a java.io.Console for you. It is in a variable named console.String response;
String response;
do {
response = console.readLine("Do you understand do while loops?");
if (response.equalsIgnoreCase("no")) {
console.printf("sorry try again");
}
}while(response.equalsIgnoreCase("no"));
I hope this will help you