你好我在创建一个名为catchAFish()的方法时遇到了麻烦,该方法从一个arraylist中随机返回一条鱼(我在其中创建了另一个添加它的方法)。如果索引为空,则将其替换为null。我的尝试在下面提供,这是我的池塘课程:
import java.util.ArrayList;
public class Pond
{
private int numFish;
ArrayList<Fish> fishes = new ArrayList<Fish>();
public int getFish() {
return this.numFish;
}
public Pond(int numFish) {
this.numFish = numFish;
}
public boolean isFull() {
return numFish == fishes.size();
}
public String toString() {
return("Pond with " + this.numFish + " Fish");
}
public void add(Fish fish) {
if(fishes.size() < this.numFish) {
fishes.add(fish);
}
}
public void listFish() {
// iterate for every fish in the fishes ArrayList
for (Fish fish : fishes) {
System.out.println(fish.toString());
}
}
public void catchAFish()
{
int randomNumber = 1 + (int) (Math.random() * fishes.size() - 1);
fishes.remove(randomNumber);
for(int j = 0; j < fishes.size(); j++)
{
System.out.println(fishes.get(j));
}
}
}
一切正常。当我将所有的鱼添加到arraylist时,它可以工作,当我只想运行程序一旦它工作正常(随机索引的鱼被删除),但当我使用以下测试器代码运行它不会。我一直在犯错。感谢任何帮助,谢谢!
public class PondTestProgram
{
public static void main(String args[])
{
//Create a pond with 10 fish
Pond pond = new Pond(15);
pond.add(new Fish(4, "Sunfish"));
pond.add(new Fish(25, "Pike"));
pond.add(new Fish(20, "Bass"));
pond.add(new Fish(30, "Perch"));
pond.add(new Fish(4, "Sunfish"));
pond.add(new Fish(15, "Pike"));
pond.add(new Fish(9, "Pike"));
pond.add(new Fish(12, "Bass"));
pond.add(new Fish(5, "Sunfish"));
pond.add(new Fish(12, "Sunfish"));
pond.listFish();
System.out.println("");
// Now catch 7 random fish
System.out.println("Catching 7 random fish as follows ...");
for (int i=0; i<7; i++)
System.out.println(pond.catchAFish());
System.out.println();
// Now show what is left in the pond
pond.listFish();
// Now try to catch 5 random fish ... but only 3 actually left
System.out.println("Catching 5 random fish as follows ...");
for (int i=0; i<5; i++)
System.out.println(pond.catchAFish());
System.out.println();
// Now show what is left in the pond
pond.listFish();
}
}
我一直在for循环中的pond.catchAfish()部分出错,我不知道为什么
答案 0 :(得分:1)
你不会从catchAFish返回鱼,所以你不能打印它。 java中的数组是零索引的 - 所以你的随机代码也是错误的。
public Fish catchAFish()
{
if (fishes.size() == 0) {
throw new Exception("No fish to be found here..");
}
int randomNumber = (int) (Math.random() * fishes.size());
return fishes.remove(randomNumber);
}
答案 1 :(得分:0)
您的catchAFish
方法返回void
。你可能想让它归还从池塘里取出的鱼。
尝试将签名更改为public Fish catchAFish()
。然后存储从列表中删除的鱼,以便返回:
Fish caught = fishes.remove(randomNumber);
…
return caught;