Michal Kowal
Michal Kowal

Reputation: 1

Correct use of labels in loops

Im looking for error in my app and it looks its here:

for (int y=0; y<MAP_HEIGHT; y+=10) {
    for (int x=0; x<MAP_WIDTH; x+=10) {
        Label:

        for (GameResource res : resources) {
            //Checks if some object is already at given point
            if (res.getArea().contains(new Point2D.Float(x, y))) { 
                continue Label;
            }
        }

        if ((int)(Math.random()*200) == 0) {
            resources.add(new GameTree(x, y));
        }

        if ((int)(Math.random()*400) == 0) {
            resources.add(new GameMine(x, y));
        }
    }
}

It creates map. I checked, and it looks that even if some object is in given point, resources are placed despite it. Have I used label correctly? If point is used I want to go to next iteraton in x-for loop.

Upvotes: 0

Views: 50

Answers (2)

arcy
arcy

Reputation: 13113

You could also do it without any label:

    for (int y=0; y<MAP_HEIGHT; y+=10) {
        for (int x=0; x<MAP_WIDTH; x+=10) {

            if (noResourcesAtPoint(resources, x, y))
            {
                if ((int)(Math.random()*200) == 0) {
                    resources.add(new GameTree(x, y));
                }

                if ((int)(Math.random()*400) == 0) {
                    resources.add(new GameMine(x, y));
                }
            }
        }
    }       


private boolean noResourcesAtPoint(GameResources resources, int x, int y)
{
    for (GameResource res : resources)
    {
        if (res.getArea().contains(new Point2D.Float(x,y)))
        {
            return false;
        }
    }
    return true;
}

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198023

If you want to go to the next iteration of the x loop, your label should be on the x loop:

Label: for (int x = 0; x < MAP_WIDTH; x += 10)

Upvotes: 1

Related Questions