I’m in computer SCI AP and I can’t figure out why this isn’t working
public static void moon(Graphics g) {
for(int k = 0; k < 550; k+=2) {
if (k == 550) {
g.setColor(Color.blue);
g.fillOval(k,50,50,50);
for(long delay = 1; delay<10000000; delay++);
g.setColor(Color.white);
g.fillOval(k,50,50,50);
k = 0;
} else {
g.setColor(Color.black);
g.fillOval(k,50,50,50);
for(long delay = 1; delay<10000000; delay++);
g.setColor(Color.white);
g.fillOval(k,50,50,50);
}
}
}
So basically is will make the black oval move across the screen then when k = 550 it will make the blue one go across the screen.. But it doesn’t do that it just moves the black one then after it hits 550 it stops.. and the blue one doesn’t come up.
Your code never reaches k = 550.
The condition in the
forloop isk < 550. Make itk <= 550and it should work.However, you may not see it happen, because you’re using
for(long delay = 1; delay<10000000; delay++);to delay – this is not a very reliable way to delay.To see things happen more reliably, try using Thread.sleep(long).
For the record, I believe there are some arguments against using
Thread.sleep(long)in general, but in this case it should suffice.While I’m at it, the
k = 0assignment is superfluous, it’s even bad style. You should not assign to a loop variable inside the loop. If the loop is entered again, thefor (int k=0part will take care of setting k to 0.HTH