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

hie can someone correct the above code for me

can someone correct the code for me

Example.java
// 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
Stanley Thijssen
22,831 Points

First 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);

Hi 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

  1. keep doing something
  2. while something is true

Here, we want to:

  1. keep prompting the user with "Do you understand while loops?" and read their answer (input)
  2. 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 :)

... thanks Lauren

You're welcome :)