Question

In the following for each loop, I get a "bird cannot be resolved" error at lines marked !. I have setup an interface Bird implemented by an abstract class BirdType of which Cardinal, Hummingbird, Bluebird, and Vulture are children. getColor() and getPosition() methods are defined in the abstract class while fly() is unique to each of the child classes. This client code was actually provided by my professor to test the interface/inheritance relations I have setup. Note I have tested the interface, abstract class and child classes and they all seem to work. I think the issue is with the for-each loop but I can provide code for the other classes if needs be. Any advice?

import java.awt.*;
public class Aviary {
    public static final int SIZE = 20;
    public static final int PIXELS = 10;

    public static void main(String[] args){
        //create drawing panel
        DrawingPanel panel = new DrawingPanel(SIZE*PIXELS,SIZE*PIXELS);
        //create pen
        Graphics g = panel.getGraphics();

        //create some birds
        Bird[] birds = {new Cardinal(7,4), new Cardinal(3,8),
            new Hummingbird(2,9), new Hummingbird(16,11),
            new Bluebird(4,15), new Bluebird(8,1),
            new Vulture(3,2), new Vulture(18,14)};

        while (true){
            //clear screen
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, SIZE*PIXELS, SIZE*PIXELS);

            //tell birds to fly and redraw birds
            for (Bird bird : birds) 
                bird.fly();
!               g.setColor(bird.getColor());
!               Point pos = bird.getPosition();
                g.fillOval((int)pos.getX()*PIXELS, (int)pos.getY()*PIXELS,
                    PIXELS, PIXELS);
                panel.sleep(500);
        }
    }
}
Was it helpful?

Solution

You need to wrap the body you want to be executed in the for loop in braces

for (Bird bird : birds) {
    bird.fly();
    g.setColor(bird.getColor());
    Point pos = bird.getPosition();
    g.fillOval((int)pos.getX()*PIXELS, (int)pos.getY()*PIXELS,
    PIXELS, PIXELS);
    panel.sleep(500);
}

Otherwise, the body of the for loop is the next statement following the ). So it is equivalent to

for (Bird bird : birds) 
    bird.fly();

// bird is not in scope anymore
g.setColor(bird.getColor());
Point pos = bird.getPosition();
g.fillOval((int)pos.getX()*PIXELS, (int)pos.getY()*PIXELS,
PIXELS, PIXELS);
panel.sleep(500);

As Darien has said in the comments, indentation is not part of the Java language, it has no bearing on the syntax. But you should use it to make your code easier to read, as expressed in the Java code style conventions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top