equalsIgnoreCase无法正常工作

equalsIgnoreCase无法正常工作

本文介绍了JAVA .equalsIgnoreCase无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在服务器类的主要方法中,我有一系列 if 语句,用于聊天程序的保留关键字,我正在尝试使用变量的值遍历它们以及 .equalsIgnoreCase 方法。问题是,即使我的变量具有某个值,执行程序时代码也始终会进入 else 子句,即使变量和变量之间存在完全匹配 if 条件。代码可以正常编译,但是我无法弄清楚为什么会这样。在开始 if 语句之前,我已经打印了变量的值,以验证变量是否具有正确的值。我的代码片段如下所示:

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

无论关键字的值是什么,它始终会选择最后的else陈述。如您所见,这将导致始终调用我的 newUser 类。我在这里想念什么吗?可能正盯着我:/

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 :/

推荐答案

您确定字符串关键字不包含任何结尾的换行符/空格或其他不可打印的字符?

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

这篇关于JAVA .equalsIgnoreCase无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:11