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 Censoring Words - Looping Until the Value Passes

Valerie Burton
Valerie Burton
602 Points

Why can't String variable = console.ReadLine(""); be placed outside the code block?

For example, the video explains that this is the proper way to declare the variable outside the code block due to scope:

String adjective;
do {
    adjective = console.readLine("Enter an adjective:  ");
if (adjective.equalsIgnoreCase("stupid") ||
    adjective.equalsIgnoreCase("dumb")) {
console.printf("That language is not allowed. Please try again. \n \n");
}
} while(adjective.equalsIgnoreCase("stupid") ||
        adjective.equalsIgnoreCase("dumb"));
console.printf("%s is a %s %s! \n \n", name, adjective, noun);

However, when I tried this instead:

String adjective = console.readLine("Enter an adjective:  ");
do {
if (adjective.equalsIgnoreCase("stupid") ||
    adjective.equalsIgnoreCase("dumb")) {
console.printf("That language is not allowed. Please try again. \n \n");
}
} while(adjective.equalsIgnoreCase("stupid") ||
        adjective.equalsIgnoreCase("dumb"));
console.printf("%s is a %s %s! \n \n", name, adjective, noun);

(sorry I don't know how to format the code properly in here)

I got "That language is not allowed. Please try again." repeated infinitely in the console. Any idea why it does this? I am new to coding. Thank you

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

When the console.ReadLine runs it asks for your input. If you put it outside the block, it will only ask for it once. Which means the value assigned to the variable will never change. Let's say you have console.ReadLine outside the while block and you read in "dumb". Because the answer is now dumb it will continually cause the loop to repeat over... and over... and over because there's no code in there to ask the user to put in something besides "dumb". That's why we put it inside the loop to give the user a chance to input something else.