Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Basics Perfecting the Prototype Censoring Words - Looping Until the Value Passes

Jonny Patterson
Jonny Patterson
7,099 Points

Using toLowerCase()

In the extra credit exercise I could only get toLowerCase() to work by doing the following:

String noun;
String badWord = "nerd"; 
boolean isInvalidWord;

      do {
        noun = console.readLine("Enter a noun:  ");
        String lower = noun.toLowerCase();
        isInvalidWord = lower.contains(badWord);
            if (isInvalidWord) {
              console.printf("That language is not allowed.  Try again.");
            }
      } while(isInvalidWord);

Whilst this appears to work correctly, I am concerned it is verbose. Is there a better way to do this?

Regarding the "bad word" list, this only appears to work with more than one word if 'noun' matches what is stored in the 'badWord' string exactly. Would the correct way to create a bad word list be to use an array?

1 Answer

Allan Clark
Allan Clark
10,810 Points

In Java just as in pure mathematics there are lots of ways to do things and not one "correct" way. I answered this problem this way:

noun = console.readLine("Enter a noun:  ");
noun = noun.toLowerCase();
while(badWord.contains(noun)) {
     noun = console.readLine("Hey thems fighting words try again: ");
}
Jonny Patterson
Jonny Patterson
7,099 Points

Thank you for taking the time to reply and sharing your solution. Helpful to see other approaches!