File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes A probability problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A probability problem" Watch "A probability problem" New topic

A probability problem

Amil Mehmedagic

Joined: Feb 27, 2004
Posts: 22
The problem requests the creation of a circle set at position (30,30).
It then needs to move at a rate of 5 pixels every 20 milliseconds to follow
a square perimeter of side 400 pixels in a clock-wise direction.
I managed to code this step, but now comes the tricky part.
At each move the circle must be capable of changing its direction with probability 0.01 (the probability of moving anti-clockwise)
This is my code:
import genesis.*;
import java.awt.*;
public class MovingCircle2 {

public static void main ( String [ ] args) {

/*Create a circle of radius 30 pixels at position(30,30).
Circle is to move at a rate of 5 pixels every 20 milliseconds to follow the perimeter of
the square (400 pixels).
Initially the circle is to move in a clockwise direction.
However at each move the circle must have a probability of 0.01 to change direction.
int x = CircleFigure.getXCentre();
int y = CircleFigure.getYCentre();

while (x != 0) {while (x != 370) {

x = x + 5;

if (x == 370) {

while (y != 370) {
y = y + 5;
if (y == 370) {

while (x != 30) {
x = x - 5;

if (x == 30) {

while (y != 30) {
y = y - 5;

How can I make sure that the circle changes direction with a probability of
0.01. I understand that a variable of type double, which stores the generated random number, needs to be created, but I am unable to pull that
section of code off!
Any help and advice on how to approach this problem would be greatly appreciated!
By the way, the class CircleFigure only has the following methods available: moveRight,moveLeft,moveUp,moveDown,moveTo,getXCentre,getYCentre.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

something like
double randomNumber = Math.random();
if (randomNumber < 0.01){

note: this is not tested in any way, it's just off the top of my head with no coffee this morning.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: A probability problem
It's not a secret anymore!