gpt4 book ai didi

java - 需要另一种方法来跟踪重量而不使用实例变量

转载 作者:行者123 更新时间:2023-12-01 11:08:49 25 4
gpt4 key购买 nike

我正在尝试找出另一种方法来跟踪手提箱的当前重量,目前我使用实例变量,但我只允许使用 2,它是手提箱中的元素列表,最大重量。

有什么方法可以做到这一点?我尝试过创建另一种方法,但我只是想不出一种不使用实例变量的方法。

我的 Suitcase.java 代码:

ArrayList<Thing> things; // List stores name of object and weight of object
private int weight; // Need to get rid of this
private int maxWeight;

public Suitcase(int weight) {
this.maxWeight = weight;
this.weight = 0; // and this?
this.things = new ArrayList<Thing>();
}

public void addThing(Thing thing) { // Need to modify this as well
if (weight < this.maxWeight) {
things.add(thing);
weight += thing.getWeight();
if (weight > this.maxWeight) {
weight -= thing.getWeight();
things.remove(things.size() - 1);
}
}
}

public Thing heaviestThing() {
if (!things.isEmpty()) {
for (int i = 0; i < things.size(); i++) {

}
}
return null;
}

public void printThings() {
for (Thing thing : things) {
System.out.println(thing);
}
}

public int totalWeight() {
return this.maxWeight;
}

@Override
public String toString() { // This is where I have problems because I need to keep track of current weight.
if (things.isEmpty()) {
return "empty (" + weight + " kg)";
} else if (things.size() == 1) {
return things.size() + " thing (" + weight + " kg)";
} else {
return things.size() + " things (" + weight + " kg)";
}
}

我的 Thing.java 代码

private String name;
private int weight;

public Thing(String name, int weight) {
this.name = name;
this.weight = weight;
}

public String getName() {
return this.name;
}

public int getWeight() {
return this.weight;
}

@Override
public String toString() {
return this.name + " (" + weight + " kg)";
}

最佳答案

为什么不创建一个方法 calculateWeight() 而不是 int maxWeight:

public int calculateWeight() {
int weight = 0;
for (Thing thing : things) {
weight += thing.getWeight();
}
return weight;
}

关于java - 需要另一种方法来跟踪重量而不使用实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606766/

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