在我的垄断游戏中,我在课堂上遇到了问题。我想知道玩家拥有多少次发货,从而确定租金。 (这是游戏的丹麦版本,所以我认为规则因国家而异)。我使用Collections.frequency但由于某种原因它总是转到else语句并给我8倍的租金。这是代码:
package fields;
import java.util.Collections;
import java.util.Scanner;
public class Shipping extends Ownable
{
public int rent;
private int occurence;
private String yesOrNo;
private Shipping shipping;
Scanner scan = new Scanner(System.in);
public Shipping(int fieldNumber, String fieldName, int price)
{
super(fieldNumber, fieldName, price);
this.rent = 500;
}
public int getRent()
{
return rent;
}
@Override
public int getPrice()
{
return price;
}
@Override
public String getName()
{
return fieldName;
}
@Override
public int getNumber()
{
return fieldNumber;
}
@Override
public matador.Player getOwner()
{
return owner;
}
@Override
public void getConsequence()
{
if(getOwner() == null)
{
System.out.println("Do you want to buy it? (Y/N)");
yesOrNo = scan.next();
if(yesOrNo.equalsIgnoreCase("y"))
{
matador.Main.currentPlayer.money -= getPrice();
owner = matador.Main.currentPlayer;
matador.Main.currentPlayer.ownedGrounds.add((Shipping) data.board[matador.Main.currentPlayer.getPosition()]);
System.out.println(matador.Main.currentPlayer.getName()
+ " bought " + getName());
}
else
{
System.out.println(matador.Main.currentPlayer.getName() +
" did not buy " + data.board[matador.Main.currentPlayer.getPosition()].getName());
}
}
else if(getOwner() != matador.Main.currentPlayer)
{
occurence = Collections.frequency(owner.ownedGrounds, shipping);
if(occurence == 1)
{
System.out.println(matador.Main.currentPlayer.getName() + " needs to pay " +
owner.getName() + " " + getRent());
matador.Main.currentPlayer.money -= getRent();
owner.money += getRent();
}
else if(occurence == 2)
{
System.out.println(matador.Main.currentPlayer.getName() + " needs to pay " +
owner.getName() + " " + (2 * getRent()));
matador.Main.currentPlayer.money -= (2 * getRent());
owner.money += (2 * getRent());
}
else if(occurence == 3)
{
System.out.println(matador.Main.currentPlayer.getName() + " needs to pay " +
owner.getName() + " " + (4 * getRent()));
matador.Main.currentPlayer.money -= (4 * getRent());
owner.money += (4 * getRent());
}
else
{
System.out.println(matador.Main.currentPlayer.getName() + " needs to pay " +
owner.getName() + " " + (8 * getRent()));
matador.Main.currentPlayer.money -= (8 * getRent());
owner.money += (8 * getRent());
}
}
}
}
我认为问题是我试图获得频率的对象,但我不知道。
提前感谢!
问候!
答案 0 :(得分:0)
occurence = Collections.frequency(owner.ownedGrounds, shipping);
Collections.frequency
依赖于对象的equals
方法来将Collection中的对象与您希望找到的对象进行比较。由于您的Shipping
课程似乎无法覆盖equals
,因此使用Object
的默认实施方式来比较参考资料。
因此,您将始终获得0
的频率(除非您传递Shipping
中已有的Collection
引用,在这种情况下,您将获得{{1}的频率但是它可能仍然是错误的结果。)
答案 1 :(得分:0)
Collections.frequency(c, o)使用equals()方法进行比较。我可以看到你没有用你自己的实现覆盖它,因此它将默认使用引用的Object.equals()。
虽然这个问题不是严格要求的should also implement .hashCode() when implementing equals()。
这是在javadoc中声明的那种。
返回指定集合中等于的元素数 指定的对象。更正式地说,返回元素的数量e 在集合中(o == null?e == null:o.equals(e))。