gpt4 book ai didi

Java:找不到符号

转载 作者:行者123 更新时间:2023-12-01 23:13:41 24 4
gpt4 key购买 nike

在这个类中,我正在制作一个 catchFish 方法,它基本上从池塘中返回一条随机鱼,应该将鱼从池塘中删除并从方法中返回,如果没有鱼,则将返回 null

这是我的代码

import java.util.Random;

public class Pond {

private int MAX_FISH = 10;
private Fish[] fish = new Fish[MAX_FISH];
private int numFish;


public Pond (int numFish, Fish[] fish) {
this.numFish = numFish;
this.fish = fish;
}


public int getNumFish() {
return numFish;
}


boolean isFull(){
if (numFish < MAX_FISH) {
return false;
} else {
return true;
}
}

public String toString(){
return "Pond with " + numFish + " fish";
}

public void listFish() {
System.out.println("Pond with " + numFish + " as follows:");
for (int i = 0; i < numFish ; i++) {
Fish f = fish[i];
System.out.println("A " + f.getSize() + " cm " + f.getSpecies());
}
}

public void add(Fish f) {
if (isFull()) {
System.out.println("Sorry, the pond is full!");
} else {
numFish++;
fish[numFish-1] = f;
}
}

public Fish catchAFish() {
if (numFish == 0) {
System.out.println("Sorry, the pond is empty!");
return null;
} else {
Fish f = new Fish();
int r = (int)Math.random()*(numFish-1);
f = fish[r];
if (r == (numFish -1)) {
fish[r] = null;
} else {
fish[r] = fish[numFish-1];
}
numFish--;
return f;
}
}
}

在 catchAFish 方法中,该行

Fish f = new Fish(); gives an error:

java:55: cannot find symbol

symbol : constructor Fish()

location: class Fish

我不明白我做错了什么?

编辑:

鱼类

public class Fish {

private String species;
private int size;


public Fish(int size, String species) {
this.size = size;
this.species = species;
}


public String toString() {
return " A " + size + " cm " + species;
}

public String getSpecies() {
return species;
}

public int getSize() {
return size;
}


}

最佳答案

基本上...Fish 必须有一个非空构造函数,要求您在创建 Fish 实例时提供一个或多个参数。

查看 Fish 代码,您提供的唯一构造函数是...

 public Fish(int size, String species) {

没有“默认”构造函数(允许您使用new Fish())。

但我不相信您实际上需要创建一个新实例,因为您几乎立即重新分配它。

 Fish f = new Fish();
int r = (int)Math.random()*(numFish-1);
// Overridden...
f = fish[r];

相反,您可以简单地使用...

 int r = (int)Math.random()*(numFish-1);
Fish f = fish[r];

关于Java:找不到符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21540931/

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