Reputation: 57
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
Reputation: 123560
What you are doing:
What you wanted to do:
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