2015-12-19 85 views
-2

這裏的情況是: 我從兩個不同的類中的兩個方法,如何比較兩種不同方法返回的值? Java的

int getBoardPositionValue(int i, int j){ //from class Board 
     return gameBoard[i][j]; 
    } 

int getCoinNumber(){ //from class Coin 
     return coinNumber; 
    } 

我想這兩個值進行比較。但是,我不確定什麼是比較它們的正確方法。

board.getBoardPositionValue(i, j)==coin.getCoinNumber() 

board.getBoardPositionValue(i, j).equals(coin.getCoinNumber()) 

或 有沒有其他的辦法嗎?

謝謝!

+2

對於原語使用'=='和引用使用'equals()'。對於雙打和浮點數,請選擇[this](http://stackoverflow.com/questions/8081827/how-to-compare-two-double-values-in-java) – TheLostMind

+0

什麼是board ..它是一個對象或類名字?..如果它是一個對象...哪一類?...這個代碼是不完整的...你如何期待我們理解? –

+2

@MathewsMathai在這種情況下並不重要。提問者想知道如何比較2種方法返回的int,而不管這些方法是如何被調用的。 – user1803551

回答

3

如果你比較引用(Objects),然後使用.equals(),但如果你比較原始類型(intfloatdouble等...),你應該使用==
在你的情況下,它看起來像你比較ints,所以你可以使用==沒有問題。
board.getBoardPositionValue(i, j) == coin.getCoinNumber()

另外:如果你想檢查兩個Object s爲的相同那麼你可以使用==,但如果你想檢查自己內容你將要使用.equals()。例如,使用相等運算符(==)而不是.equals()方法檢查兩個Strings是否相等是錯誤的。
檢查了這一點對於使用.equals()==的一個典型的例子中String

 String a = "abc"; 
     String b = "abc"; 

     // returns true because a and b points to same string object 
     if(a == b){ 
      System.out.println("Strings are equal by == because they are cached in the string pool"); 
     } 

     b = new String("abc"); 

     // returns false as now b isn't a string literal and points to a different object 
     if(a == b){ 
      System.out.println("String literal and String created with new() are equal using =="); 
     }else{ 
      System.out.println("String literal and String created with new() are not equal using =="); 
     } 

     //both strings are equal because their content is the same 
     if(a.equals(b)){ 
      System.out.println("Two Strings are equal in Java using the equals() method because their content is the same"); 
     }else{ 
      System.out.println("Two Strings are not equal in Java using the equals() method because their content is the same"); 
     } 
+2

感謝您的解釋! :)這真的很有幫助! – Andrew

1

對象A和對象B. A==B被用於檢查中的對象reference.If兩個物體的術語是相同的參考相同的地址,它將返回true。 (B)用於比較對象的相等性。如果兩個對象具有相同的實例變量並且實例變量的值相等,那麼它將返回true。 如果實例變量的值相同,則相同類的對象相等。

基元: int a = 1;和int b = 3; a==b檢查是否相等。在這種情況下,它返回false。