[英]java can't compare strings
我寫了一個從套接字讀取一行的代碼。
如果該行是“再見”,我希望它輸出“ nice”。 由於某種原因它不起作用,盡管我確實嘗試無條件輸出輸入,並且確實說“再見”
這是我的代碼
String input = null;
if (socket.getInputStream().available() > 0)
input = in.readLine();
if (input != null)
{
input = input.trim();
if (input == "bye")
out.println("nice");
out.println(input);
}
使用String#equals()
而不是==
來比較字符串。
if (input != null)
{
input = input.trim();
if (input.equals("bye"))
out.println("nice");
out.println(input);
}
equals()
比較字符串的內容。
您想要您的內心是否這樣說:
if (input.equals("bye"))
代替
if (input == "bye")
==
實際上是在比較參考對象(有點像指針),有時在插入字符串時可能會起作用,但這是另一個主題。 使用.equals()
!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.