user1588867
user1588867

Reputation: 67

Returning the result of comparing two strings using 'contains'

So, I've got two strings being input and the subString looked for in the mString. When I change the method to boolean it returns the correct output of true or false (by using return on the contains statement).

I don't know how to use that statement to check the outcome of that contains operator. I've got the following done up.

public class CheckingString
{

    public static void main(String[] args)
    {
        // adding boolean value to indicate false or true
        boolean check;

        // scanner set up and input of two Strings (mString and subString)
        Scanner scan = new Scanner(System.in);
        System.out.println("What is the long string you want to enter? ");
        String mString = scan.nextLine();
        System.out.println("What is the short string that will be looked for in the long string? ");
        String subString = scan.nextLine();

        // using the 'contain' operator to move check to false or positive.
        // used toLowerCase to remove false negatives
        check = mString.toLowerCase().contains(subString.toLowerCase());

        // if statement to reveal resutls to user
        if (check = true)
        {
            System.out.println(subString + " is in " + mString);
        }
        else
        {
            System.out.println("No, " + subString + " is not in " + mString);
        }
    }

}

Is there a way to make that check field work properly to return a value in the if-else statement?

Upvotes: 0

Views: 639

Answers (4)

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

Try it

 if (check) {
        System.out.println(subString + " is in " + mString);
    } else {
        System.out.println("No, " + subString + " is not in " + mString);
    }

Upvotes: 0

Code-Apprentice
Code-Apprentice

Reputation: 83577

The preferred way to use a boolean variable in an if statement is

if (check)

Note that you don't need to use an equality operator, which avoids the error which you made.

Upvotes: 0

PC.
PC.

Reputation: 7024

the trivial mistake:

change if(check = true) to if(check == true) or just if (check)

by doing check = true you are assigning true to check so the condition if(check = true) will always be true.

Upvotes: 5

TofuBeer
TofuBeer

Reputation: 61546

if (check = true){

should be:

if (check == true){

Normally you would write:

if(check)

to check for true

and:

if(!(check)) 

or:

if(!check)

to check for false.

Upvotes: 5

Related Questions