2014-03-28 109 views
0

我是一個極端的編碼noob,我剛剛開始。我設計了一款搖滾紙剪刀遊戲,但無法弄清楚爲什麼它不起作用。由於某些原因,用戶輸入在if語句中不起作用。請看一下。使用「==」時字符串比較失敗?

package com.youtube.njillatactics; 

    import javax.swing.JOptionPane; 

    public class RPS { 
public static void main(String args[]){ 
    //start message 
    JOptionPane.showMessageDialog(null, "Welcome to Nick's rock paper scissors game!"); 
    //get user input and convert to lower case 
    String userInput = JOptionPane.showInputDialog("Choose rock, paper, or scissors.").toLowerCase(); 
    //generate random computer input 
    double computerInput = Math.random(); 
    //match user input to converted computer input 
    JOptionPane.showMessageDialog(null, match(userInput, convert(computerInput))); 
} 
//convert random computer input into choice 
public static String convert(double x){ 
    if(x < 0.33){ 
     return "rock"; 
    }else if(x < 0.66){ 
     return "paper"; 
    }else 
     return "scissors"; 
} 
//check to see who wins 
public static String match(String x,String y){ 
    if(x == y){ 
     return "Tie!"; 
    }else 
    if(x == "rock"){ 
     if(y == "paper"){ 
      return "Computer wins!"; 
     }else 
      return "User wins!"; 
    } 
    if(x == "paper"){ 
     if(y == "scissors"){ 
      return "Computer wins!"; 
     }else 
      return "User wins!"; 
    } 
    if(x == "scissors"){ 
     if(y == "rock"){ 
      return "Computer wins!"; 
     }else 
      return "User wins!"; 
    }else 
     return x + ", " + y; 
} 
} 
+0

哇。這很簡單。就像我說的,我是新人,所以謝謝你幫助我。那很快! – user3461740

+1

爲了將來的參考,如果您花時間確定_what_明確無效,這將會很有幫助。你沒有告訴我們這些症狀,更不用說一個特定的代碼片段,當你認爲它會做另一件事時做了一件事情。 – yshavit

回答

5

你比較==字符串時,你應該將它們與.equals(s)

而是來比較,例如,

if(y == "rock") { 

改變它

if(y.equals("rock")) 

(您還應該確保y不是null要麼通過測試,或嘗試捕它。)

==比較字符串的計算結果爲真,如果相同的字符串對象是在==的兩側。

equals(s)比較字符串比較它們的值,無論它們是同一個對象...顯然,如果他們發生是同一個對象,它總是會評估爲true

+2

另一個變化是'if(「rock」.equals(y))' – csmckelvey

+1

「[Yoda條件](http://blog.codinghorror.com/new-programming-jargon)。」 – yshavit

+2

即使我完全支持你的回答,用戶可能並不總是完全「搖滾」,所以你也可以做y.equalsIgnoreCase(「rock」);這會讓玩遊戲的人更具普遍性 – user2277872

1

在java中,您不會比較兩個字符串x == y。相反,您使用x.equals(y)進行比較。這解釋了爲什麼這些if語句不起作用。