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

2015/1/21

Getting a random number between 10.0 and 15.0 but with decimals?

DiplomatikCow DiplomatikCow

2015/1/21

#
I want to have all my fireworks (yes, I am creating a scenario that just shoots fireworks) have a velocity between 10.0 and 15.0 yet include all decimals to a tenth. How can I do so
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
public class Rocket extends SmoothMover
{
    Color randomColor = new Color(Greenfoot.getRandomNumber(255), Greenfoot.getRandomNumber(255), Greenfoot.getRandomNumber(255), 255);
    private int Direction = Greenfoot.getRandomNumber(40)+210;
    public Rocket()
    {
       setRotation(Direction);
       GreenfootImage image;
       image = new GreenfootImage(10,10);
       image.setColor(randomColor);
       image.drawOval(0,0,10,10);
       image.fillOval(0,0,10,10);
       setImage(image);
    }
    public void act()
    {
        // Add your action code here.
    }   
}
danpost danpost

2015/1/22

#
Well, this:
1
int rand = 100+Greenfoot.getRandomNumber(51);
would set rand to an int value between 100 and 150. So,
1
double speed = (double)rand/10.0;
should do it. You could also do this:
1
double speed = 10.0+Math.random()*5.0;
to include an infinite number of speeds between 10 and 15.
DiplomatikCow DiplomatikCow

2015/1/22

#
And how would I proceed to input that value into a method in which the firework moves in its given direction at that random speed>
danpost danpost

2015/1/22

#
Presuming the parameter of the method is of type double, you can just insert the expression on the right of my last assignment statement.
DiplomatikCow DiplomatikCow

2015/1/22

#
What......I don't understand doubles at all..... :(
danpost danpost

2015/1/22

#
The SmoothMover class probably has a 'public void move(double distance)' method, or something like that. If so, you can just do:
1
2
3
4
// add instance field
private double speed = 10.0+Math.random()*5.0;
// and in act method
move(speed);
You need to login to post a reply.