如何比较从两个不同方法返回的两个值?JAVA
情况如下: 我有两个不同班级的两种方法如何比较从两个不同方法返回的两个值?JAVA,java,compare,equals,Java,Compare,Equals,情况如下: 我有两个不同班级的两种方法 int getBoardPositionValue(int i, int j){ //from class Board return gameBoard[i][j]; } int getCoinNumber(){ //from class Coin return coinNumber; } 我试图比较这两个值。然而,我不确定什么是比较它们的正确方法 board.getBoardPositionValue(
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()
或
或
还有别的办法吗
谢谢 如果比较引用(对象
),则使用.equals()
,但如果比较基本类型(int
,浮点
,双精度
等),则应使用=
。
在您的情况下,看起来您正在比较
整数
,因此可以毫无问题地使用=
。(
board.getBoardPositionValue(i,j)==coin.getCoinNumber()
)
进一步:如果要检查两个
对象是否相同,则可以使用=
,但如果要检查它们的内容,则需要使用.equals()
。例如,使用相等运算符(=
)而不使用.equals()
方法检查两个字符串是否相等是错误的。
查看此示例,了解在字符串中使用.equals()
或=
的经典示例:
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");
}
对象A和对象B。
A==B
用于检查对象在引用方面是否相同。如果两个对象引用相同的地址,则返回true
A.equals(B)用于比较对象的相等性。如果两个对象具有相同的实例变量,并且实例变量的值相等,则返回true。
如果同一类的对象的实例变量具有相同的值,则它们是相等的
原语:
INTA=1;int b=3;
a==b
检查是否相等。在本例中,它返回false。对于原语,使用==
;对于引用,使用equals()
。对于double和float,请检查什么是board.。它是对象还是类名?。如果它是对象…属于哪个类?…此代码不完整…您希望我们如何理解?@MathewsMathai在这种情况下并不重要。询问者想知道如何比较从两个方法返回的int
s,而不管这些方法是如何调用的。你试过了吗?第二个为你编译了吗?当你尝试它时发生了什么?哦,你没有?在发帖前不尝试真的更有效吗?谢谢你的解释!:)这真的很有帮助!
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");
}