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 - 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);}