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 trialJoseph Saika
2,648 Pointshie can someone correct the above code for me
can someone correct the code for me
// 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? ");
}
if (response.equals(no));{
console.printf("Try again");}
while (response.equalsIgnoreCase("no"));
console.printf("Because you said %s, you passed the test!", response);
3 Answers
Stanley Thijssen
22,831 PointsFirst of all, your if statement should be placed inside your do block and should check for the string "no". Now you are checking whether the response is equal to a variable called no which is wrong. You should also remove the ';' after your if statement, this doesn't belong there.
so your code should look something like this:
String response = "";
do {
response = console.readLine("Do you understand do while loops? ");
if (response.equals("no")) {
console.printf("Try again");
}
} while (response.equalsIgnoreCase("no"));
console.printf("Because you said %s, you passed the test!", response);
Lauren Moineau
9,483 PointsHi Joseph. Adding to Stanley Thijssen's answer, you don't really need a "Try again" prompt here. You can just let the do-while loop do its job.
In a do-while loop, we want to
- keep doing something
- while something is true
Here, we want to:
- keep prompting the user with "Do you understand while loops?" and read their answer (input)
- while their answer is "no"
String response = "";
do {
response = console.readLine("Do you understand do while loops? ");
} while (response.equalsIgnoreCase("no"));
If the answer is not "no", we leave the do-while loop and print:
console.printf("Because you said %s, you passed the test!", response);
So in the end, you get:
String response = "";
do {
response = console.readLine("Do you understand do while loops? ");
} while (response.equalsIgnoreCase("no"));
console.printf("Because you said %s, you passed the test!", response);
Hope that helps :)
Joseph Saika
2,648 Points... thanks Lauren
Lauren Moineau
9,483 PointsYou're welcome :)