【发布时间】:2015-04-13 20:17:15
【问题描述】:
我正在编写一个程序,允许用户将狗签入狗窝,但我在打印所有喜欢骨头的狗时遇到了一些麻烦(添加狗时数组列表中的标准之一)。当您从主控制台菜单中选择“打印所有喜欢骨头的狗”选项时,我试图仅打印名称,但它正在打印数组列表中的所有信息。
这是当前代码:
private void printDogsWithBones() {
Dog[] dogsWithBones = kennel.obtainDogsWhoLikeBones();
System.out.println("Dogs with bones: ");
for (Dog d: dogsWithBones){
System.out.println(d);
}
}
public Dog[] obtainDogsWhoLikeBones() {
// TODO
// Prints "null" if a dog is in the array that doesn't like bones.
Dog[] tempResult = new Dog[dogs.size()];
// Sets the int tempResult to -1 to allow for scanning through the array from position 0, making sure every dog is accounted for.
int tempCount = -1;
// For each loop to scan through the array and check for each dog that likes bones
for (Dog t : dogs){
// Adds 1 to tempCount to enable efficient and functional scanning through the array
tempCount++;
// Adds the animal from the array to the temp Array which will then be printed back in KennelDemo
if(t.getLikesBones() == true){
tempResult[tempCount] = t;
}
}
return tempResult;
}
我遇到的另一个问题是,如果狗不喜欢骨头,它会打印出“null”而不是什么都没有。
这是运行该方法时控制台打印的内容:
1 - add a new Dog
2 - set up Kennel name
3 - print all dogs who like bones
4 - search for a dog
5 - remove a dog
6 - set kennel capacity
q - Quit
What would you like to do:
3
Dogs with bones:
null
Dog name:RoverLikes Bones?:trueOriginal Owner:[David 98765]Favfood:NipplesFoodPerDay:3
Dog name:IzzyLikes Bones?:trueOriginal Owner:[Jay 123456789]Favfood:CurryFoodPerDay:3
提前谢谢大家。
【问题讨论】: