0
我目前正在学习Java编程,并在练习String contains(),它用于检查字符串中是否存在特定的字符串。但是在给定的代码中,即使字符串存在,contains()也会返回false。即使字符串存在,Java中的字符串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()'只返回一个单词,而不是整行。另外,请勿为每个输入使用新的“扫描仪”。行为可能不是你所期望的。 – ajb
我的猜测是,扫描仪输入的分隔符有些问题。 –
在'else'后添加以下内容,你会看到会发生什么:'System.out.printf(“s1:”+ s1 +“; s2:”+ s2 +“;”);' – alfasin