import java.util.Random; // Warn compiler we want to use Random class /** * Demonstrates how to create and use instances of the Random class. */ public class Randomness { /** * Print a random number between (and including) 1 and * the specified value. * @param max The largest possible number to be randomly generated */ public void printRandomNumber(int max) { Random rng; rng = new Random(); // nextInt(max) returns something 0..(max-1). Adding 1 turns // that into 1..max. System.out.println(rng.nextInt(max)+1); } /** * Print "heads" or "tails". */ public void flipACoin() { Random rng; rng = new Random(); if (rng.nextBoolean()) { System.out.println("Heads"); } else { System.out.println("Tails"); } } /** * Picks a random letter out of a string and returns it * as a char. * @param s The string from which to select a letter * @return A char that is a letter from s */ public char randomCharacter(String s) { Random rng = new Random(); int index = rng.nextInt(s.length()); return s.charAt(index); // For now } }