如果满足条件,则打印数组列表的 select 部分

Printing select sections of an array list if a condition is met

我正在编写一个允许用户将狗登记到狗舍的程序,但我在打印所有喜欢骨头的狗时遇到了一些问题(添加狗时数组列表中的标准之一) .当您从主控制台菜单 select 选择 "print all dogs who like bones" 选项时,我试图只打印名称,但它正在打印数组列表中的所有信息。

这是当前代码:

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

提前谢谢大家。

那是因为您跳过了狗不喜欢骨头的 tempResult 数组中的数组索引。即使狗不喜欢骨头,您也会增加 tempCount,因此当前值将被跳过。要修复,请将 tempCount 增量移动到 if 语句中。

if(t.getLikesBones() == true){
    tempCount++;
    tempResult[tempCount] = t;
}

此外,由于 t.getLikesBones() 的计算结果为真,您不需要 == 真。您也可以在数组索引上使用前缀增量,但这会降低可读性。

if(t.getLikesBones()){
    tempResult[++tempCount] = t;
}

在创建时不知道数组大小的情况下使用数组通常建议您应该使用列表。这将为您动态调整自身大小。如果您随后想转换回一个很好的数组,但也许列表而不是数组更适合您的整个应用程序

public Dog[] obtainDogsWhoLikeBones() {    

    // Initialise dogsWhoLikeBones list
    ArrayList<Dog> dogsWhoLikeBones = new ArrayList<Dog>();

    // Iterate through dogs
    for (Dog dog : dogs){
        if(dog.getLikesBones()){
            // If a dog likes bones, add them to the list
            dogsWhoLikeBones.add(dog);
        }
    }

    // Get size of list to set the size of the return array
    int listSize = dogsWhoLikeBones.size();

    // Convert dogs list back to an array
    return dogsWhoLikeBones.toArray(new Dog[listSize]);
}

要打印出狗的名字而不是 java 尝试将您的对象转换为字符串,在打印 for 循环中您需要获取它的名字。你的狗 class 中有这个访问器吗(例如 getName)?如果是这样你可以这样做:

for (Dog d: dogsWithBones){
    System.out.println(d.getName());
}