如何让Scanner从用户输入中挑选关键字



如果用户输入的是"外面很冷"而不仅仅是"冷",程序就会移动到else语句(就像它应该做的那样(。如何让它在不知道用户输入的情况下运行并挑选关键词?

System.out.println("I am doing well, thank you!  How's the weather today?");
String s = scan.nextLine();
if (s.equalsIgnoreCase("cold") || s.equalsIgnoreCase("freezing")) {
System.out.println("You'd better bundle up");                
} else {
System.out.println("Stay cool");
}   

尝试:

if (s.contains("cold") || s.contains("freezing"))

这里contains()方法搜索字符串中的字符序列。如果找到字符值的序列,则返回true。

注意:equalsIgnoreCase方法根据字符串的内容比较两个字符串,而不考虑它们的大小写。

您可以使用indexOf检查输入中是否有关键字,如下所示:

Scanner scan = new Scanner(System.in);
System.out.println("I am doing well, thank you!  How's the weather today?");
String s = scan.nextLine();
if (s.indexOf("cold")>-1 || s.indexOf("freezing")>-1) {
System.out.println("You'd better bundle up");                
} else {
System.out.println("Stay cool");
}   

您需要使用contains和toLowerCase。例如:

System.out.println("I am doing well, thank you!  How's the weather today?");
String s = scan.nextLine();
if (s.toLowerCase().contains("cold") ||  s.toLowerCase().contains("freezing")) {
System.out.println("You'd better bundle up");                
} else {
System.out.println("Stay cool");
}   

最新更新