所以我是编码/ Java的新手,我正在研究这个项目。我的任务是创建3个不同的类(我在这里)并使它们合作。我已经成功地让我的FishTankManagerApp
类检索了一个新的Fish
对象,并且我正试图弄清楚如何将它放在FishTank
对象中。
我的FishTank
类仅用于创建一个可以容纳5条鱼的数组对象(我想我已经正确完成了)。在我的FishTankManagerApp
课程中,我创建了一个包含10个这些FishTank
对象的数组。
我无法弄清楚我的生活的问题是,如何将Fish
个对象放置在一个特定的FishTank
对象之后(我已经在我遇到问题的代码的结尾。)
基本上我知道我正在尝试将我创建的对象放在其中,并且数组中包含另一个可以存储鱼对象的数组......我想....
任何帮助将不胜感激!谢谢!
import java.util.Scanner;
public class Fish {
private static Scanner stdin = new Scanner(System.in);
private String userInput;
private int userInput2;
public boolean mean;
public String name;
public Fish(){
System.out.println("What is your fishes name?");
userInput = stdin.next();
this.name = userInput;
System.out.println("Is this fish aggressive?\n"+
"(1)Yes\n(2)No");
userInput2 = stdin.nextInt();
if (userInput2 == 1)
this.mean = true;
else
this.mean = false;
}
}
public class FishTank {
public FishTank(){
Fish[] tank = new Fish[5];
}
}
import java.util.Scanner;
public class FishTankManager {
private static Scanner stdin = new Scanner(System.in);
private static int userInput;
private static FishTank[] tanks = new FishTank[10];
public static void main (String[] args) {
while (true){
System.out.println("Welcome to your new fish tank manager!\n"+
"What would you like to do?\n"+
"(1)Add a Fish\n(2)Move a Fish\n"+
"(3)Check a tank");
userInput = stdin.nextInt();
if (userInput == 1){
Fish fish = new Fish();
System.out.println(fish.name);
System.out.println(fish.mean);
changeTank(fish);
}
else if(userInput ==2){
}
else{
}
}
}
private static void changeTank(Fish fish){
System.out.println("Which tank would you like to put this fish in? (1-10)");
userInput = stdin.nextInt();
tanks[userInput] = fish;
// This last line is where I'm confused on how to put the fish() object into a tank which I've created.
}
}
答案 0 :(得分:3)
我建议您在FishTank
添加方法,以便轻松添加鱼。也许是这样的:
public FishTank(){
private Fish[] tank = new Fish[5];
public boolean addFish(Fish fish) {
// ... add code here to put the fish to the tank array
// return true if there was room in the tank, false otherwise
}
}
请注意,tank
变量现在是私有的。在Java中保持成员变量私有是一个好主意,并使用方法来访问它们。
然后,如果你收到了你提到的评论,你可以调用新方法:
boolean addedSuccessfully = tanks[userInput].addFish(fish);
你可能不需要像我显示的那样返回布尔值,但是如果你需要检查阵列(即坦克)是否有新鱼的空间,它可能会很方便。
答案 1 :(得分:1)
目前,您正在做的是将FishTank对象设置为等于Fish实例 - 而不是将其添加到FishTank内的tank变量。
现在,您无法访问FishTank类中的tank变量。您需要做的是使其成为全局变量并提供访问器/修改器方法。例如:
public class FishTank {
private Fish[] tank;
private int numFish;
public FishTank(){
this.tank = new Fish[5];
this.numFish = 0;
}
public void add(Fish f){
if(this.numFish >= 5){
//handle "tank is full" case
}
else{
numFish++;
this.tank[numFish] = f;
}
}
}
然后在所需的FishTank对象上调用add:
坦克[userInput]。新增(鱼);