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