Results 1 to 4 of 4
Thread: for loop not working?
- 07-24-2012, 02:28 PM #1
Member
- Join Date
- Jul 2012
- Posts
- 33
- Rep Power
- 0
for loop not working?
Hi
I'm doing the Stanford cs 106a course and am stuck on what must be a very simple oversight.
The exercise I'm doing requires a simple program to create random circles on a canvas with random radius, color etc. 10 circles. I've started the program just to test it, without worrying about getting all 10 precisely within the canvas. But there's an unexpected hitch- it only creates one circle. As far as I can see the "for" loop I've written should make 10 method calls and get ten returns- unless I've misunderstood something. I've gone back through the book etc but can't find anything that contradicts my thought process. Here's what I've written;
import acm.program.*;
import acm.graphics.*;
import acm.util.*;
import java.awt.*;
public class RandomCircles extends GraphicsProgram {
private RandomGenerator rgen = RandomGenerator.getInstance();
public void run() {
int radius = rgen.nextInt( 25, 250);
int positionx = rgen.nextInt(getWidth());
int positiony = rgen.nextInt(getHeight());
Color nextcolor = rgen.nextColor();
for (int i = 0; i < 10; i++) {
add(createCircle(positionx, positiony, radius, nextcolor));
}
}
private GOval createCircle(int x, int y, int r, Color color) {
GOval circle = new GOval(x, y, r, r);
circle.setColor(color);
circle.setFilled(true);
return circle;
}
}
Could someone let me know what I've done wrong? Thanks!
Robbie
- 07-24-2012, 02:34 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Re: for loop not working?
Many classes and methods which I dont know, but you never change the parameter for the createCircle method or?
(positionx, positiony, radius, nextcolor) are still the same!
You have to change these in your loop! Otherwise you draw ten times the same circle -> looks like one :D
- 07-24-2012, 02:38 PM #3
Member
- Join Date
- Jul 2012
- Posts
- 33
- Rep Power
- 0
Re: for loop not working?
Of course! So instead of defining variables which use the random generator, I put the random generator into the brackets after the method call? Makes sense I guess, ta, I'll give it a pop...
- 07-24-2012, 02:55 PM #4
Member
- Join Date
- Jul 2012
- Posts
- 33
- Rep Power
- 0
Similar Threads
-
for loop stops working
By name in forum New To JavaReplies: 5Last Post: 04-17-2012, 04:53 PM -
Loop not working
By swilliams236 in forum New To JavaReplies: 2Last Post: 11-07-2011, 10:36 PM -
for loop not working properly
By lbgladson in forum New To JavaReplies: 8Last Post: 10-15-2011, 12:33 AM -
Why isn't this while loop code working
By GreenTea in forum New To JavaReplies: 16Last Post: 11-10-2010, 03:14 AM -
while loop not working
By RBNSN83 in forum New To JavaReplies: 6Last Post: 06-21-2010, 07:29 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks