问题
In the main method of my server class I have a series of if
statements for the reserved keywords of a chat program which I am trying traverse using the value of a variable along with the .equalsIgnoreCase
method. The problem is that even though my variable holds a certain value, when executing the program the code always steps into the else
clause even if there is an exact match between the variable and one of the if
conditions. The code compiles fine but I just cant figure out why this is happening. I have printed the value of the variable just before commencing the if
statements to verify it held the correct value. A snipet from my code is shown below:
System.out.println("Keyword is : " + keyword);
if (keyword.equalsIgnoreCase("who"))
{
System.out.println("calling who function");
whoFunction(address, socket, port);
}
else if (keyword.equalsIgnoreCase("whoami"))
{
whoami(address, socket, port, clientAddress);
}
else if (keyword.equalsIgnoreCase("all"))
{
all(message);
}
else if (keyword.equalsIgnoreCase("Bye"))
{
bye(address, socket, port, clientAddress);
}
else
{
newUser(keyword, address, searchListLength, clientAddress, port);
}
No matter what the value of the keyword is, it always resorts to selecting the final else statement. As you can see this will result in always call my newUser
class. Am I missing something here? Probably staring me in the face :/
回答1:
Are you sure that the String keyword
does not contain any trailing newline/spaces or other nonprintable characters?
回答2:
There could be leading/trailing spaces in your input, which would cause a non-match.
Try adding this statement at the top:
keyword = keyword.trim();
回答3:
Also see Collator
The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text.
- https://docs.oracle.com/javase/8/docs/api/java/text/Collator.html
- Performing Locale-Independent Comparisons
来源:https://stackoverflow.com/questions/11605422/java-equalsignorecase-not-working