Reputation: 17
I am currently learning programming in Java and was practicing the String contains(), which is used to check whether a particular string within a string exists or not. But in the given code, the contains() returns false even if the string is present.
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.");
}
}}
Upvotes: 0
Views: 897
Reputation: 26
String s1 = sc1.next();
will only take one word i.e. I
in your case because of the occurrence of a space.
However if you use sc1.nextLine();
, the whole sentence will be taken, i.e. "I am a boy". Thereby solving your problem.
Upvotes: 1