Pergunta

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.

Foi útil?

Solução

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)
}

Outras dicas

Here's another way of implementing it:

public class Grid {

private int numRows;
private int numCols;
private List<Location> locations;

public Grid() {
    this.locations = new ArrayList<Location>();
}

public Flower get(Location loc) {
    Flower flower = null;
    for(Location location: locations) {
        if(location.getRowValue() == loc.getRowValue() 
                && location.getColValue() == loc.getColValue()) {
            flower = location.getFlower();
            break;
        }
    }
    return flower;
}

public int getTotalFlowers() {
    int total = 0;
    for(Location location: locations) {
        if(location.getFlower()!=null) {
            total++; 
        }
    }
    return total;
}

// ... put your getters and setters here

}

And here's the Location class

public class Location {

private int rowValue;
private int colValue;
private Flower flower;

// ... put your getters and setters here

}

It is assumed that you would be populating the grid with Locations and some of those locations will have flowers and some won't.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top