Java 如何在此Kennel类中完成addDog、removeDog和toString方法?
我只是想得到一些关于如何在我必须用Java完成的kennel类中完成这些方法的输入 这对你们大家来说可能很简单,但我目前不确定从哪里开始,所以非常欢迎任何指导 代码如下:Java 如何在此Kennel类中完成addDog、removeDog和toString方法?,java,arrays,tostring,Java,Arrays,Tostring,我只是想得到一些关于如何在我必须用Java完成的kennel类中完成这些方法的输入 这对你们大家来说可能很简单,但我目前不确定从哪里开始,所以非常欢迎任何指导 代码如下: public class APCS_5_2 { public static void main(String[] args) { Kennel myKennel = new Kennel(); //myKennel.addDog(new Dog("dog1", 0);
public class APCS_5_2 {
public static void main(String[] args) {
Kennel myKennel = new Kennel();
//myKennel.addDog(new Dog("dog1", 0);
//myKennel.addDog(new Dog("dog2", 1);
//myKennel.addDog(new Dog("dog3", 2);
//myKennel.addDog(new Dog("dog4", 3);
//myKennel.addDog(new Dog("dog5", 4);
//System.out.println(myKennel);
//myKennel.removeDog(2);
//System.out.println(myKennel);
}
}
/*
“犬舍笼子”或阵列应始终从0开始填充,并在此处输入代码。
当一只新狗被添加到犬舍时,它应该进入下一个可用的“笼子”或索引
当一只狗被移走时,它的斑点必须填满,因此如果“笼子3”中的狗被移走
如果有狗的话,这个笼子需要用更高编号的“笼子”里的狗来填满
当犬舍打印出来时,它应该只显示所有填充的笼子
*/
我当然希望您发布一些代码尝试,但由于您提到需要指导,请参阅下面的一个非常快速的尝试,以重新创建addDog()。我没有进行太多测试,这是未完成的,但如果您愿意,请接受答案,然后我希望共同完成此任务:) 请阅读
class Kennel {
private Dog[] dogs;
public Kennel() {
dogs = new Dog[10];
}
/* complete addDog
complete this method so that it adds the passed in Dog object to the next available "cage" represented by the next null array index in dogs
In thinking through this you might need to add additional class level variables to properly facilitate this functionality
*/
public void addDog(Dog d) {
}
/* complete removeDog
complete this method so that the Dog with the id that is passed in is removed from the "Kennel"
when a dog is removed it's spot must filled so if the dog in "cage 3" were removed
that cage would need to be filled in with a dog from a higher numbered "cage" if there are any
*/
public Dog removeDog(int id) {
return new Dog("remove this and replace with the proper code" , -100);
}
/* complete toString
for each "cage" should output as below for cage 1 or index 0 of the array
cage: 1
name: dog1
id: 0
*/
public String toString() {
String str = "";
return str;
}
}
class Dog {
private String name;
private int id;
public Dog(String n, int id) {
name = n;
this.id = id;
}//constructor
public void setName(String n) {
name = n;
}
public String toString() {
return "Name\t"+name+"\nID:\t"+id;
}
}//APCS_5_2
class Kennel {
private Dog[] dogs;
private int availableCageIndex = 0;
private int maxCageIndex=10;
public Kennel() {
dogs = new Dog[10];
}
public void addDog(Dog d) {
if((availableCageIndex) ==maxCageIndex)
return;//no space
dogs[availableCageIndex] = d;
availableCageIndex++;
}