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!

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 - Using Logical ORs

Double if's.

So within the video I learned how to block someone from saying a certain word, or even multiple words. But.. While testing this I found out that if you type multiple of the blocked words it would allow them to continue, for example.

if (noun.equalsIgnoreCase("dork") || noun.equalsIgnoreCase("jerk")) { console.printf("You are not allowed to say that! Exiting. \n \n"); System.exit(0); }

This is the code that I wrote, which will kick the user out for saying dork or jerk when asking for a noun, how do I make it kick them out if they say both words instead of one like, "dork, jerk or dork jerk".

You could search the input string for any occurrence of a word like "jerk". The obvious downside to this would be false positives for an input string like "beef jerky" which has the word jerk in it.

I think a slightly better approach would be to split the input string by spaces into an array of strings. Then you could loop through the array and look for exact matches on the words you don't want.

2 Answers

Dennis Mårtensson
Dennis Mårtensson
7,400 Points

You could try using the String methods "toLowerCase()" and "contains()". They do pretty much what they sound like they are doing. By first shifting the string to lower case it makes it easy for you to compare, and then check if the string contains a blocked word. Something like this should work, but I'm no expert, haha.

if (noun.toLowerCase().contains("dork") || noun.toLowerCase().contains("jerk"))
     //Do stuff
Chaz Hall
Chaz Hall
1,970 Points

Question, the .toLowerCase() method, what class(not sure if this is the right term) would that be under? I know the course went over noun.equalsIgnoreCase() , but I saw no mention of toLowerCase. Any help would be great! Thanks!

Thanks for your code it worked, but he is right, its going to target any work with 'jerk' and dork' within it. Thank you both though!