如何在网格中找到Flower对象的数量?

时间:2014-01-22 00:24:15

标签: java object gridworld

首先,我对我提出这个问题的方式感到非常抱歉。这出现在我班级正在进行的练习评估中,我不知道它的要求是什么或如何开始。这是一个问题:

GridWorld中的Grid对象具有getNumRows和getNumCols方法,这些方法分别返回网格中的行数和列数。 Grid对象还有一个方法get(Location,loc),它返回位置loc的actor,如果该位置未被占用,则返回null。编写一个返回网格中Flower对象数的方法。

任何朝着正确方向的推动都会很棒,再一次对不起有多么糟糕。 谢谢。

2 个答案:

答案 0 :(得分:4)

这样的事情可能就是你想要的。不确定程序是否正确,因为我不熟悉GridWorld或代码中的其他对象。

然而,基础是双循环,循环遍历每一行,并且每行循环遍历列,从而覆盖整个网格。

正如您所看到的,我将isFlowerAt方法留空了,因为我不知道grid.get()会返回什么。

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

答案 1 :(得分:0)

这是实现它的另一种方式:

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

}

这是位置类

public class Location {

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

// ... put your getters and setters here

}

假设您将使用位置填充网格,其中一些位置将有鲜花,有些则不会。