• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

A probability problem

Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
lowercase baba
Posts: 12751
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!