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 trialAndrew Stewart
533 PointsWhy 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
1 Answer
Seth Barton
1,275 PointsHi 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!
ghvr5
Android Development Techdegree Student 307 Pointsghvr5
Android Development Techdegree Student 307 PointsThat problem starts here:
console.printf("bad word\n Try again\n");
is not within the scope of theif
statement, so it will run regardless of whether theif
statement's condition istrue
orfalse
. Furthermore, nouns being entered into thenoun
variable will not be equal to the default values oftrue
orfalse
forinvalidWord
, so the first block of code will not run again.