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

Morten Hauge
Morten Hauge
9,240 Points

Would it be ideal to use an array, if so, how?

In this lesson we censor different words. Wouldn't it make more sense to use an array such as "censoredWords" and use an if statement like this?

if (userAnswer.equalsIgnoreCase(censoredWords)) { System.exit(0); }

So that you wouldn't have to use the || operator for every single word? How would one do this in Java?

2 Answers

You could do something like this:

import java.util.*;

public class Censor {

   public static void main(String[] args) {
      ArrayList<String> censoredWords = new ArrayList<>();
      Collections.addAll(censoredWords, "dork", "jerk", "stupid", "idiot", "moron");
      String userAnswer = "Hey jerk, your answer is stupid";  //in lieu of console input from user
      ArrayList<String> foundWords = new ArrayList<>();

      for (String word : censoredWords) {  
         if (userAnswer.contains(word)) {
            foundWords.add(word); 
         }
      }
      System.out.println("Answers cannot contain the word: " + foundWords.toString());
   }
}

Output would be: Answers cannot contain the word: [jerk, stupid]

Of course, this is a quick take. It shouldn't all be in the main() method. It should get user input from Console or Scanner. It should call an overridden toString() method, etc.

Hi Morten! As Craig mentions in the extra credit another way to censor is to use string.contains like this;

String badWords = "jerk nerd dork"; String userAnswer = console.readLine("Enter word: "); if (badWords.contains(userAnswer){System.exit(0);}