Random Behavior


The Random Class


Example: Using a Random Number to Drive Random Behavior

Consider a program simulating a person at lunch who randomly chooses between a cookie or an apple for dessert.

Example: Choosing Randomly
student.takeASandwich();
student.takeCoffee();
Random generator = new Random();
int randNum = generator.nextInt(2);
if ( randNum == 0 )
    student.takeAnApple();
else
    student.takeACookie();
student.sitDownAndEat();

Alyce Brady, Kalamazoo College