gpt4 book ai didi

java - 脏话过滤器 : I just need some help on how to make it recognize _only_ the values in an array

转载 作者:行者123 更新时间:2023-11-30 02:38:28 25 4
gpt4 key购买 nike

    /*

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

我只是很难找到我需要的适当的异常(exception)。我知道我已经非常接近了,但是在尝试了很多个小时来解决这个问题并且没有得到一个将为我需要的实例(数组中的实例)返回 true 的解决方案之后,我也很累了。你能指出我在这里做错了什么或者没有正则表达式的正确解决方案吗?

我已经尝试过休息了;当我将 boolean 标志设置为 true 但它不起作用后,它会继续迭代,因此输出始终为 false。

谢谢!

最佳答案

这是一个可能的解决方案:

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

这是一个流式 java8 版本:

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

关于java - 脏话过滤器 : I just need some help on how to make it recognize _only_ the values in an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42446637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com