2013-02-27 49 views
0

所以我的問題是我試圖做一個非常簡單的程序來刷新我可怕的編碼技能,但我遇到了一個我不明白的問題。該程序應該回答「是」並打印「耶」,只是爲了檢查它是否工作,但它不起作用。所以我想知道我做錯了什麼。掃描nextLine()似乎並沒有改變字符串

public class main { 
    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     int playerTroops, computerTroops; 
     String teamName, computerName = "Orcs", answer; 
     Scanner listener = new Scanner(System.in); 
     System.out 
       .println("Welcome to the Battle Grounds, where you are responsible for winning a war \nAre you ready? \nYes or No"); 
     answer = listener.nextLine(); 

     if (answer == "Yes") 
      System.out.println("Yayy"); 
     else 
      System.out.println("Why"); 
    } 
} 

回答

4

對於Java字符串比較,您必須使用.equals操作:

if(answer.equals("Yes")) 

如果你想忽略大小寫,

if(answer.equalsIgnoreCase("Yes")) 

在Java中,運營商==檢查參考平等。在正常情況下,等於字符串不會自動具有相同的引用(I.E:它們是不同的對象,這種區別在Java中非常重要)。

+0

哦,謝謝你的工作 – user2113591 2013-02-27 02:12:27

+0

@ user2113591歡迎來到SO。不要忘記[接受](http://meta.stackexchange.com/a/5235/186652)回答是否可以解決您的問題(時限過後)。 – Pshemo 2013-02-27 02:24:29