Anand Raina
Anand Raina

Reputation: 17

String contains () in Java returns false even if string is present

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.");
    }
}}

Output screen

Upvotes: 0

Views: 897

Answers (1)

sushantPatil
sushantPatil

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

Related Questions