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 trialLuis Ignacio Gomez
567 PointsI do not know:
How to tell the console "hey, if the answer is "no", keep runing without using an "isInvalidWord" loop. Also Idk how to put that a while loop.
I feel like I do not know nothing :(
// 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? ");
}
2 Answers
Ivan Penchev
13,833 PointsThe logic of do-while can be found here: https://www.tutorialspoint.com/cprogramming/images/cpp_do_while_loop.jpg
Basically you do something, atleast once and then check for the condition.
So lets see what you have? well you do indeed have what to do:
do {
response = console.readLine("Do you understand do while loops? ");
}
but you are missing the condition.
How can we add the condition?? Lets check the documentation, its located here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html The Java programming language also provides a do-while statement, which can be expressed as follows:
do {
statement(s)
} while (expression);
so we need a while? OK!
so what should the condition be? Lets read your requirements: "How to tell the console "hey, if the answer is "no", keep runing "
So what is the "console" its an special object that we use that gives us input in the 'response ' variable. So for our condition we must evaluate that
in short, the answer is this:
do {
response = console.readLine("Do you understand do while loops? ");
} while (response.equals("No"))
Be sure to vote this answer if it was helpful, or leave a comment if you have more questions.
Raffael Dettling
32,999 PointsThe while condition comes after the last } and use the equals methode to compare to strings and don´t use response == "NO" i made that mistake :) Everything else looks good ^^
}while(response.equals("No"));
Why you sould use equals => https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
Ivan Penchev
13,833 PointsThanks mate, nice catch with the equals method, I edited my answer because of you :) Been a long time since I used Java.
Raffael Dettling
32,999 PointsYou´re welcome :) I usually use the == operator too. Instead of using methods :D It´s way quicker
Luis Ignacio Gomez
567 PointsLuis Ignacio Gomez
567 PointsThank you very much, your answer was very helpful! :)