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

Andrew Stewart
Andrew Stewart
533 Points

Why doesn't this method work?

When my code is:

String noun; Boolean invalidWord; String name = console.readLine("Enter a name: "); String adjective = console.readLine("Enter an adjective: "); do{ noun = console.readLine("Enter a noun: "); invalidWord = (noun.equals("dork") || noun.equals("jerk")); if(noun.equals(invalidWord)); console.printf("bad word\n Try again\n");

     } while(noun.equals(invalidWord));

This code compiles and after typing dork for noun I get the message "bad word, try again." However, instead of looping it goes right into asking me adverb and so on. I understand that it works if I have if(invalidWord) and while(invalidWord) instead of what is above. I just don't understand why the other method will not work.

Thanks

That problem starts here:

if (noun.equals(invalidWord));
console.printf("bad word\n Try again\n");

console.printf("bad word\n Try again\n"); is not within the scope of the if statement, so it will run regardless of whether the if statement's condition is true or false. Furthermore, nouns being entered into the noun variable will not be equal to the default values of true or false for invalidWord, so the first block of code will not run again.

1 Answer

Seth Barton
Seth Barton
1,275 Points

Hi Andrew!

The problem has to do with data types and scope. When you use a method, such as .equals() with type String, it's expecting you to pass it a variable of type String in its parentheses. In your code, you've passed it a variable of type Boolean, which is either equal to true or false. The String "noun" will probably never be equal to either of those values, so the if statement will never be run.

The reason your code kept running instead of looping back and prompting for the noun again is because you forgot to scope the if statement. (AKA. put {} around what you want to do if the statement were true).

Hope that helps!