Reputation: 321
/*
Profanity Filter:
- Cat
- Dog
- LLama
- Has to differ cases, like cAt
- Has to differ words that contain the words to be filtered, "Cataclysm", for example. Hello, World of Warcraft.
*/
import java.util.Scanner;
public class ProfanityFilter
{
public static void main (String[] args)
{
Scanner kb = new Scanner(System.in);
String userInput, toLowerCase;
boolean flag = false;
int i;
String[] list = new String[12];
list[0] = "cat";
list[1] = " cat";
list[2] = "cat ";
list[3] = " cat ";
list[4] = "dog";
list[5] = " dog";
list[6] = "dog ";
list[7] = " dog ";
list[8] = "llama";
list[9] = " llama";
list[10] = "llama ";
list[11] = " llama ";
System.out.println("Enter a string:");
userInput = kb.nextLine();
toLowerCase = userInput.toLowerCase();
for (i = 0; i < list.length; i++)
{
if(toLowerCase.contains(list[i]) | toLowerCase.equals(list[i]))
{
flag = true;
}
}
if (flag)
{
System.out.println("Something you said is forbidden.");
}
else
{
System.out.println("Nothing was found");
}
}
}
I'm just having trouble finding the proper exception to what I need. I know I'm pretty close, but I'm also tired after trying many many hours to solve this problem and coming out empty of a solution that will return true for the instances I need (the ones in the array). Can you point me out to what I'm doing wrong in here or to a proper solution without regular expressions?
I've already tried to put a break; after I turn the boolean flag to true but it didn't work, it keeps iterating and thus the output keeps being false.
Thanks!
Upvotes: 1
Views: 540
Reputation: 5103
Here is a potential solution:
public class Class {
private static final String[] profaneWords = {
"cat",
"dog",
"llama"
};
public static void main(String... args) {
System.out.println(isProfane("this is some user input."));
System.out.println(isProfane("this is some user input containing the dirty word 'Cat'."));
System.out.println(isProfane(" cat "));
System.out.println(isProfane("Cat"));
}
private static boolean isProfane(final String input) {
for (final String profanity : profaneWords) {
if (input.toLowerCase().contains(profanity)) {
return true;
}
}
return false;
}
}
Here is a streaming java8 version:
import java.util.Arrays;
public class Class {
private static final String[] profaneWords = {
"cat",
"dog",
"llama"
};
private static boolean isProfane(final String input) {
return Arrays.stream(profaneWords)
.anyMatch(input.toLowerCase()::contains);
}
}
Upvotes: 2