我已经尝试了所有事情,我仍然无法使这个代码正常运行
public void Action(ActionEvent event)
{
//We get the text from the textfield
String fromUser = textfield1.getText();
if (fromUser != null) {
if(x<1)
{
if(fromUser.length() <= 10)
{
USERNAME = fromUser;
x++;
textfield1.setText("");
}
else
{
textarea1.setText("Username Surpasses Size Limit Please Try Again\nUsername Must Be 10 Characters Or Less");
textfield1.setText("");
}
}
else
{
if(x==1)
{
textarea1.setText("");
x++;
}
//We append the text from the user
textarea1.append(USERNAME+"> " + fromUser + "\n");
//The pane auto-scrolls with each new response added
textarea1.setCaretPosition(textarea1.getDocument().getLength());
//We reset our text field to "" each time the user presses Enter
textfield1.setText("");
//This is Where my code should work
if(fromUser == "n")
{
InitiateText("North");
}
else if(fromUser == "s")
{
InitiateText("South");
}
else if(fromUser == "w")
{
InitiateText("West");
}
else if(fromUser == "e")
{
InitiateText("East");
}
else
{
InitiateText("I don't comprehend");
}
}
}
}
public void InitiateText(String Where) //Where are you on the map
{
//We append the text from the user
textarea1.append("Map > " + Where + "\n");
//The pane auto-scrolls with each new response added
textarea1.setCaretPosition(textarea1.getDocument().getLength());
//We reset our text field to "" each time the user presses Enter
textfield1.setText("");
}
这是我最近尝试做的事情,添加文字的方法工作正常,但if语句不起作用,我输入&#34; n&#34;并且它不会识别&#34; n&#34;我输入了。我做错了什么?
答案 0 :(得分:4)
将if(fromUser == "n")
更改为if(fromUser.equals("n"))
并使用equals()
方法而不是==
更改每个语句以比较字符串。
==
运算符只是检查引用是否引用相同的字符串对象,它们不检查String
的相等性。阅读String comparison with equals and assignment operator