我对编程很陌生,本周我的任务是基于 Java 中的对象。
在这之前是我的代码
public class Animal {
float mass;
String name;
int legs;
// Exercise 6-6
public Animal(String randomName) {
name = randomName;
legs = 0;
mass = 0;
}
// Exercise 6-7
public Animal(float one, String two, int three) {
mass = one;
name = two;
legs = three;
}
//Exercise 7
public String toString(){
return "name =" + name + "legs=" + legs + "mass=" + mass;
}
public void massSetter() {
}
public String getName() {
return name;
}
public int getLegs() {
return legs;
}
}
然后有这个
public class Zoo {
private Animal[] park;
// Exercise 9
public Zoo() {
Animal[] park = new Animal[10];
}
// Exercise 10
public void addAnimal(Animal first) {
for (int i = 0; i < 10; i++) {
if (park[i] != null) {
park[i] = first;
i = 10;
} else if (i == 9) {
System.out.println("The zoo is full!");
}
}
}
// Exercise 11
public void feed() {
for (int i = 0; i < 10; i++) {
park[i].mass *= 1.1;
}
}
public String toString() {
return "The zoo is capable of keeping " + park.length + "animals"
+ '\n'
+ "The following is the list of animals currently in the zoo."
+ '\n' + "cage 1 status: " + park[0] + '\n' + "cage 2 status: "
+ park[1] + '\n' + "cage 3 status: " + park[2] + '\n'
+ "cage 4 status: " + park[3] + '\n' + "cage 5 status: "
+ park[4] + '\n' + "cage 6 status: " + park[5] + '\n'
+ "cage 7 status: " + park[6] + '\n' + "cage 8 status: "
+ park[7] + '\n' + "cage 9 status: " + park[8] + '\n'
+ "cage 10 status: " + park[9];
}
public void print() {
System.out.println(park.toString());
}
public int totalLegs() {
int totalLeg = 0;
for (int i = 0; i < 10; i++) {
totalLeg += park[i].legs;
}
return totalLeg;
}
}
最后
public class TestZoo {
public static void main(String[] args){
Zoo zoo = new Zoo();
}
}
我有两个问题。
首先,从 Zoo 类中的 toString 方法可以看出,我的 return 语句太长了。我尝试使用 for 循环,但我似乎无法在 return 语句中真正做到这一点,所以我想知道是否有更简单的方法。
第二个问题是,练习告诉我用大象和蜘蛛之类的名称填充我在 TestZoo 类中创建的对象动物园。我想知道我怎么能做到这一点。