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 trialJonathan Trinh
1,426 PointsLast exercise challenge 2/3
I do not understand this questions how do you continually prompt the user in a do while loop. And declare a response outside of the do while loop? .
// I have initialized a java.io.Console for you. It is in a variable named console.
do {
String response = console.readLine ("Do you understand do while loops?");
String response; do{
reponse = promt;
} while (response.equals("No");
2 Answers
michaelcodes
5,604 PointsSo what we did was declare the String variable response outside of the "do".
String response;
do {
response = console.readLine ("Do you understand do while loops?");
}
The reason we declare the String outside of it is because of something in java called "scope" of the variable.
If we use (string response = console.readLine) we can't use our variable anywhere else aside from inside the do { }. This is not very useful to us.
So by first declaring the String outside of the do { }
String response;
It allows us to access it further down in the code. Since we just declared the variable, we don't need to include "String" again when we set it to a value:
response = console.readLine ("Do you understand do while loops?");
Hope this helps! if you have any other questions let me know.
michaelcodes
5,604 PointsHi there! In order to print the response outside of the do-while loop you must declare the variable "response" outside of the scope of the do-while loop. This is known as the "scope" of the variable.
String response; //declared outside of the scope so we can access it later on outside the do-while
do {
response = console.readLine ("Do you understand do while loops?");
} while (response.equals("No")); //once this is NOT equal to "No" the loop will end
//and the program continues
//So now we can print out the line, because response is declared outside the scope (Part 3 of challenge)
console.printf("Because you said %s, you passed the test!", response);
Hope this helps! happy coding!
Jonathan Trinh
1,426 Pointsdo { response = console.readLine ("Do you understand do while loops?"); } while (response.equals("No"));
Okay I got it thank you, another question is why was the String in (string response = console.readline) was remove?? so now its just (response = console.readline)???
Jonathan Trinh
1,426 PointsJonathan Trinh
1,426 PointsHey thanks a lot this makes perfect sense to me now :)