This site requires JavaScript, please enable it in your browser!
Greenfoot back
SlaySlig
SlaySlig wrote ...

2015/7/7

Creating Loop method for painting stars on World class

SlaySlig SlaySlig

2015/7/7

#
I'm trying to create a loop that will paint 300 random stars(2 pixel dots) onto my World subclass Space. I'm finding it impossible to understand Loops without any Layman's terms (on the internet) explaining what the code means or stands for. So far I have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public Space()
 {
     super(600, 400, 1);
     GreenfootImage background = getBackground();
     background.setColor(Color.BLACK);
     background.fill();
     createStars();
 }
 public void createStars()
 {
     GreenfootImage background = getBackground();
     background.setColor(Color.BLACK);
     background.fill();
     background.setColor(Color.WHITE);
     background.fillOval(Greenfoot.getRandomNumber(600),Greenfoot.getRandomNumber(400),2,2);
 }
...I'm not so much interested in the answer, but the path to finding it. Any help would be appreciated.
davmac davmac

2015/7/7

#
Well, I'd use a "for" loop for this kind of task. The "official" Java tutorials covers for loops here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html The "ForDemo" class on that page has a simple loop which counts from 1 to 10. You could replace the body of that loop with the code to draw a star (line 15 in the code you pasted) and you'd pretty much be done, I think. If you have trouble understanding that, I think the way forward is for you to identify precisely what it is that you're having trouble grasping (i.e. what is the first sentence in the above tutorial that doesn't make sense to you?)
AD999 AD999

2015/7/8

#
1
2
3
for (int i = 0; i < 300; i++) {
createStars();
}
int i = 0 is the counter variable (while) i < 300 The statement will keep looping until i < 300 is false i++ increases the variable i by 1 every time the loop executes Simple explanation. Should read more tutorials and play around with the code to understand it better.
You need to login to post a reply.