Im just starting Java course and professor have asked us to fill out the window with small circles making it look like stars. We need to use Math.random()*MAX to set the random amount and size with a given limit.
I have been trying different things but I feel so lost with Java. I have also look for examples online but they are all about random numbers.
gc.fillRect(0, 0, 400, 400);
gc.setFill(Color.WHITE);
gc.fillOval(50, 60, 2, 2);
gc.fillOval(150, 200, 2, 2);
gc.fillOval(150, 100, 3, 3);
gc.fillOval(230, 220, 3, 3);
gc.fillOval(80, 200, 2, 2);
gc.fillOval(350, 200, 2, 2);
gc.fillOval(300, 250, 2, 2);
gc.fillOval(320, 350, 2, 2);
gc.fillOval(20, 320, 2, 2);
Instead of having all this lines repeat with different values I believe the Math.random is supposed to do it but im not sure how to use it properly, or how to implement it properly to my problem. Any example or guidance is more than welcome.
CodePudding user response:
You can set a pane as parent of the circle shapes . E.g. pane 400 width and 300 heigth . Those are the maxinum random number to translate in x and y axis . Also you can set radius of circles at random number e.g. 5 as max random number . You can make a for loop and make a new circle instance with those random number as arguments in circle`s constructor in each iteration and add it as child of pane
CodePudding user response:
Math.random() is pretty straight forward.
int nrOfStars = 20; // you choose your parameters
int maxSizeX = 400;
int maxSizeY = 400;
int maxWidth = 10;
int maxHeight = 10;
int posX;
int posY;
int width;
int height;
gc.fillRect(0, 0, maxSizeX, maxSizeY);
gc.setFill(Color.WHITE);
for (int i = 0; i < nrOfStars; i ) {
posX = (int) (Math.random() * maxSizeX);
posY = (int) (Math.random() * maxSizeY);
width = (int) (Math.random() * maxWidth);
height = (int) (Math.random() * maxHeight);
System.out.println(
"x: " posX " | y: " posY " | height: " width " | height " height);
}
Although I do recoment you youse nextInt() like:
Random r = new Random();
// for...
posX = r.nextInt(maxSizeX);
posY = r.nextInt(maxSizeY);
width = r.nextInt(maxWidth);
height = r.nextInt(maxHeight);