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 trialRodrigo Teixeira
1,417 PointsWhy it wasn't needed to declare the variable question outside the loop?
As it was said in Java Basics, the variables needed to be declared outside of the loop so that we are able to use them inside of it. But in this case, the variable question is only declared inside of the loop and the program is still working. How can it be possible? Thank you in advance =D.
2 Answers
Grigorij Schleifer
10,365 PointsHI Rodrigo,
In a class definition, there are three kinds of variables.
- instance (global) variables - Any method in the class definition can access these variables
- parameter variables - Only the method where the parameter appears can access these variables.
- local variables - Only the method where the parameter appears can access these variables.
Lets focus on global and lokal variables:
So if you create a variale outside the loop you can use it in the code outside and inside the loop This variable is global. In other words the scope of the glopal variable is wide.
If your variable has been created inside the loop (lokal variable) the scope is restricted to the loop (or it can be a method) and you can use it only inside the loop/method
Makes sense?
Grigorij
Sabrina Manneh-Velázquez
Courses Plus Student 732 PointsHi Rodrigo, The variable 'question' is specifically part of the while loop code itself. It only needs to exist if somebody answers 'yes' to the anyQuestions variable. At this point we enter the loop code where the 'question' variable is used. The 'question' variable doesn't need to be declared outside of the loop because it's not actually used in any code outside of the while loop.
Sabrina