JAVA .equalsIgnoreCase 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11605422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:45:34  来源:igfitidea点击:

JAVA .equalsIgnoreCase not working

javaif-statementconditional-statements

提问by Joe Murphy

In the main method of my server class I have a series of ifstatements for the reserved keywords of a chat program which I am trying traverse using the value of a variable along with the .equalsIgnoreCasemethod. The problem is that even though my variable holds a certain value, when executing the program the code always steps into the elseclause even if there is an exact match between the variable and one of the ifconditions. 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 ifstatements to verify it held the correct value. A snipet from my code is shown below:

在我的服务器类的 main 方法中,我有一系列if针对聊天程序的保留关键字的语句,我正在尝试使用变量的值和.equalsIgnoreCase方法遍历这些语句。问题是,即使我的变量具有某个值,在执行程序时,else即使变量与if条件之一完全匹配,代码也总是会进入子句。代码编译得很好,但我无法弄清楚为什么会发生这种情况。我在开始执行if语句之前打印了变量的值,以验证它是否保存了正确的值。我的代码中的一段代码如下所示:

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 newUserclass. Am I missing something here? Probably staring me in the face :/

不管关键字的值是多少,它总是选择最后的 else 语句。正如你所看到的,这将导致总是给我的newUser班级打电话。我在这里错过了什么吗?可能正盯着我的脸:/

回答by Marco Leogrande

Are you sure that the String keyworddoes not contain any trailing newline/spaces or other nonprintable characters?

您确定该字符串keyword不包含任何尾随换行符/空格或其他不可打印的字符吗?

回答by Bohemian

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();

回答by Christophe Roussy

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.

Collat​​or 类执行区域设置敏感的字符串比较。您可以使用此类为自然语言文本构建搜索和排序例程。