Why can't Java resolve the variable in this for each loop? -
in following each loop, "bird cannot resolved" error @ lines marked !. have setup interface bird implemented abstract class birdtype of cardinal, hummingbird, bluebird, , vulture children. getcolor() , getposition() methods defined in abstract class while fly() unique each of child classes. client code provided professor test interface/inheritance relations have setup. note have tested interface, abstract class , child classes , seem work. think issue for-each loop can provide code other classes if needs be. 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 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 fly , redraw birds (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); } } }
you need wrap body want executed in 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, body of for
loop next statement following )
. equivalent to
for (bird bird : birds) bird.fly(); // bird 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 comments, indentation not part of java language, has no bearing on syntax. should use make code easier read, expressed in java code style conventions.
Comments
Post a Comment