javaobjectgridworld

How to find the number of Flower objects in a grid?


First off, I am very sorry about the way I am asking this question. This came up on a practice review my class is doing, and I have no idea really what its asking for or how to begin. Here is the question:

A Grid object in GridWorld has getNumRows and getNumCols methods, which return the number of rows and the number of columns in the grid, respectively. A Grid object also has a method get(Location, loc), which returns the actor at location loc, or null, if the location is unoccupied. Write a method that returns the number of Flower objects in grid.

Any push in the right direction would be great, once again sorry how poorly this is being asked. Thank you.


Solution

  • Something like this is probably what you are looking for. Not sure about the correctness of the program as I'm not familiar with GridWorld or the other objects in your code.

    The basics are however the double loop, looping over each row and for each row looping over the column thus covering the whole grid.

    As you can see I left the isFlowerAt method empty since I have no idea what grid.get() will return.

    int counter = 0;
    for (int row  = 0; row < grid.getNumRows(); row++) {
        for (int col = 0; col < grid.getNumCols(); col++) {
            if (isFlowerAt(grid, row, col)){
                counter++;
            }
        }
    }
    return counter;
    
    private boolean isFlowerAt(Grid grid, int row, int col) {
        //Return true if a flower is located at (row, col)
    }