2017-08-24 61 views
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."); 
    } 
}} 

Output screen

+7

'Scanner'上的'next()'只返回一个单词,而不是整行。另外,请勿为每个输入使用新的“扫描仪”。行为可能不是你所期望的。 – ajb

+0

我的猜测是,扫描仪输入的分隔符有些问题。 –

+1

在'else'后添加以下内容,你会看到会发生什么:'System.out.printf(“s1:”+ s1 +“; s2:”+ s2 +“;”);' – alfasin

回答

1
String s1 = sc1.next(); 

只需要一个字即I你的情况,因为空间的发生。

但是,如果您使用sc1.nextLine();,则将采取全部句子,即“我是男孩”。从而解决您的问题。

+0

谢谢,这正是我所期待的。 –