2017-08-24 171 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

謝謝,這正是我所期待的。 –