gpt4 book ai didi

java - 无法从 HashSet 中的类调用方法

转载 作者:行者123 更新时间:2023-12-01 19:17:48 37 4
gpt4 key购买 nike

我想做的是总结危险类别中的影响值

例如,它将遍历居住者列表,找到危险并从中获取影响量。然后将所有危险的总影响相加,并将该值返回给我。

下面有洞穴类危险类抽象居住者类

当向洞穴添加危险时,它就会成为 HashSet 中的占用者。当尝试使用 getImpact() 方法获取能量水平时,无法访问该方法,因为它是在 Hazard 而不是 Occupant 中。

我还有另外两个类也扩展了 Occupant。 玩家元素

在添加到 HashSet 时,我找不到将危险保留为 Hazard 类的方法,以便可以使用 getImpact() 方法。

在添加到 HashSet 时,这还需要满足其他类 Player 和 Item 的需要。

<小时/>
public class Cave {

HashSet<Occupant> occupants;
private double impact;

/**
* Creat a new Cave instance with no occupants.
*/
public Cave()
{
occupants = new HashSet<Occupant>();
}

/**
* Adds an occupant to a Cave if the occupant is not already there and
* if cave currently has fewer than the maximum number of occupants.
* @param occupant, the occupant to add
* @return true if successfully added
*/
public boolean addOccupant(Occupant occupant) {
boolean validNewOccupant = occupant != null;
boolean enoughRoom = occupants.size() < MAX_OCCUPANTS;
if (validNewOccupant && enoughRoom) {
validNewOccupant = occupants.add(occupant);
}

return validNewOccupant && enoughRoom;
}

/**
* Gets the sum of the impact from all hazards in the cave
* @returns hazardEnergyImpact
*/
public double getHazardEnergyImpacts(){
double energyImpact = 0.0;
for( Occupant occupant : occupants ){
if(occupant.toString() == "!"){
energyImpact += occupant.getImpact();
}
}
return energyImpact;
}
}
<小时/>
public abstract class Occupant {

private Address address;
private String name;

/**
* Construct an occupant for a known address & name.
* @ param row, row of address
* @ param column, row of address.
* @ param name, occupant's name
*/
public Occupant(Address address, String name) {
this.address = address;
this.name = name;
}

@Override
public String toString(){
return "";
}
}
<小时/>
public class Hazard extends Occupant  {

private String longDescription;
private double impact;

/**
* Construct a hazard with know attributes
* @param row
* @param column
* @param name
* @param longDescription
* @param impact
*/
public Hazard(Address address, String name, String longDescription, double impact) {
super(address, name);
this.longDescription = longDescription;
this.impact = impact;
}

@Override
public String toString(){
return "!";
}

/**
* gets impact amount
* @returns impact
*/
public double getImpact(){
return this.impact;
}
}

最佳答案

另一种选择是将 getImpact() 方法添加到 Occupant,例如,

public double getImpact() {
return 0.0;
}

Hazard@Override 实现的 getImpact() 只会将其 impact 实例变量返回为你已经设置好了。然后,您的循环被简化为:

public double getHazardEnergyImpacts() {
double energyImpact = 0.0;
for( Occupant occupant : occupants ) {
energyImpact += occupant.getImpact();
}
return energyImpact;
}

如果您稍后需要提取到适当的接口(interface)抽象,现代 IDE 可以让这变得简单,这是件好事。

关于java - 无法从 HashSet 中的类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5812912/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com