【发布时间】:2018-02-01 19:37:57
【问题描述】:
我目前正在学习Java编程,正在练习String contains(),它用于检查字符串中的特定字符串是否存在。但是在给定的代码中,即使字符串存在, contains() 也会返回 false。
import java.util.*;
class StringPractice1{
public static void main(String arg[]){
System.out.println("Enter a string:- ");
Scanner sc1 = new Scanner(System.in);
String s1 = sc1.next();
System.out.println("Enter the string you want to find:- ");
Scanner sc2 = new Scanner(System.in);
String s2 = sc2.next();
if(s1.contains(s2)){
System.out.println("It contains the string '"+s2+"'.");
}
else{
System.out.println("No such string exists.");
}
}}
【问题讨论】:
-
Scanner上的next()只返回一个词,而不是整行。另外,不要对每个输入都使用新的Scanner。行为可能不是您所期望的。 -
我的猜测是扫描仪输入的行分隔符有问题。
-
在
else块之后添加以下内容,您会看到会发生什么:System.out.printf("s1:"+s1+"; s2:"+s2+";"); -
@ajb 我认为你是对的,这是 next() 的问题,因为它对句子的起始词返回 true。感谢您的帮助。