candylady
candylady

Reputation: 57

Java startsWith dont work properly

I got a table of two strings:

String[] tab = {"why","Why"};

And I want to it them to see if somebody is asking a question with different words than those in my tab[]:

for (int i = 0; i < tab.length; i++) {
            if(!message.startsWith(tab[i])){
                System.out.println("Ask using why or Why");
                break;      
            }
            }

When I'm typing my input: "Why the weather is bad?", it returns: "Ask using why or Why". Also when I type: "How are you?", it return "Ask using why or Why".

I want this program to allow only question that starts with why or Why.

What am I doing wrong?

Upvotes: 0

Views: 1038

Answers (1)

that other guy
that other guy

Reputation: 123560

What you are doing:

  1. Match against the first entry
  2. If it doesn't match, show the message to the user and abort.

What you wanted to do:

  1. Match against the first entry.
  2. If it doesn't match, try the next entry.
  3. If no entries matched, show a message to the user and abort.

Here's an example:

boolean found = false;

for (int i = 0; i < tab.length; i++) {
    if(message.startsWith(tab[i])){
        found = true;
        break;
    }
}

if (!found) {
    System.out.println("Ask using why or Why");
}

In your particular instance, you can also just check the lowercase version of the string:

if (!message.toLowerCase().startsWith("why")) {
    System.out.println("Ask using why or Why");
}

Upvotes: 3

Related Questions