ucodebro3
ucodebro3

Reputation: 1

How do I use the contains method with "if, else" statement?

I am having difficulty triggering my "if" statement. When I input "I like my 'anything'", which the CharSequence should be searching for, the code kicks out the error from the else statement. I've tried to see if the contains method wasn't reading whitespace by attempting to identify just one letter using the CharSequence. That didn't help. I also attempted to change my contains method into a boolean and run the if statement if the boolean were true. That also did not work. I've searched around a bit at other code and it seems to look similar. Eclipse isn't flagging any errors I'm just beginning and have little clue on what else to attempt. If there are any additional hints on how to clean my code up or methods that might work better. Please give some constructive criticism.

import java.util.Scanner;

public class hello {

    public static void main(String args[]) {

        Scanner scan = new Scanner(System.in);
        try {
            System.out.println("Hi, what is your name?");
            String name1 = scan.next();
            System.out.println("Hello "+ name1 + ". Tell me what you like about yourself?\n"
                    + "Please pretext what you like about yourself with the phrase 'I like my'.");
            String selfEsteem = scan.next();
            CharSequence searchString = "I Like my";

            if (selfEsteem.contains(searchString)) {
                selfEsteem = selfEsteem.replace("my", "your");
                System.out.println(selfEsteem + "also.");
            } else {
                System.err.println("Error: User did not use 'I like my' input format");
            }
        } finally {
            scan.close();
        }
    }

}

output:

Hi, what is your name? Janet Hello Janet. Tell me what you like about yourself? Please pretext what you like about yourself with the phrase 'I like my'. I like my boobs Error: User did not use 'I like my' input format

Upvotes: 0

Views: 17195

Answers (3)

Kevin Anderson
Kevin Anderson

Reputation: 4592

Use

if (selfEsteem.containsIgnoreCase(searchString))
    ...

instead of

if (selfEsteem.contains(searchString))
    ...

Then it doesn't matter what case the user types in.

Upvotes: -2

user6499716
user6499716

Reputation:

You are searching for "I Like my" while your error massages says it should be 'I like my'.

It's case sensitive.

Either type in "I Like my" or change your searchString to "I like my".

Upvotes: 1

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27466

Your searchString is "I Like my", while your text has "I like my". So I assume your user will enter the lowercase one and contains is case sensitive so it won't find it.

Change to:

CharSequence searchString = "I like my";

Upvotes: 1

Related Questions