java 审查词条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27242582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Censored Words Condition
提问by beginnercoder010812
I need this program to print "Censored" if userInput contains the word "darn", else print userInput, ending with newline.
如果 userInput 包含单词“darn”,我需要这个程序打印“Censored”,否则打印 userInput,以换行符结尾。
I have:
我有:
import java.util.Scanner;
public class CensoredWords {
public static void main (String [] args) {
String userInput = "";
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine;
if(){
System.out.print("Censored");
}
else{
System.out.print(userInput);
}
return;
}
}
Not sure what the condition for the if can be, I don't think there is a "contains" method in the string class.
不确定 if 的条件是什么,我认为字符串类中没有“包含”方法。
回答by TheLostMind
回答by Sarthak Mittal
Try this:
试试这个:
if(userInput.contains("darn"))
{
System.out.print("Censored");
}
Yes that's right, String class has a method called contains, which checks whether a substring is a part of the whole string or not
是的,没错,String 类有一个名为 contains 的方法,它检查子字符串是否是整个字符串的一部分
回答by maxx777
Java String Class does have a containsmethod. It accepts a CharSequence
object. Check the documentation.
回答by Cat
Another beginner method would be to use the indexOf function. Try this:
另一种初学者方法是使用 indexOf 函数。试试这个:
if (userInput.indexOf("darn") > 0) {
System.out.println("Censored");
}
else {
System.out.println(userInput);