Java Paint if x = location do this else do this

蓝咒 提交于 2019-12-11 06:09:32

问题


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.


回答1:


Your code never reaches k = 550.
The condition in the for loop is k < 550. Make it k <= 550 and 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 = 0 assignment is superfluous, it's even bad style. You should not assign to a loop variable inside the loop. If the loop is entered again, the for (int k=0 part will take care of setting k to 0.

HTH




回答2:


You will always enter the else path, because your for loop counts from 0 to 549, so k will never be equal to 550.




回答3:


for(int k = 0; k < 550; k+=2)

will loop but k will not enter the loop with the value of 550 so your if statement will not be executed at all

use this

for(int k = 0; k <= 550; k+=2)



回答4:


k will never be 550, because your expression is k < 550.

Either change it to k <= 550 or move the 550 part outside of the loop entirely.

IMO it doesn't really belong in the loop if it only happens once and the other n hundred times it doesn't. Better to have an inner loop for all the rest, and an outer loop that makes it run forever rather than modifying the loop variable.



来源:https://stackoverflow.com/questions/8386779/java-paint-if-x-location-do-this-else-do-this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!