/* Author: Stephanie Elzer * Date: February 2, 2007 * Purpose: To demonstrate using the Random class to generate a pseudorandom phone number * Solving programming exercise #3 from Chapter 3 */ import java.util.*; import java.text.*; public class Phone { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Declare a Random variable, generator, and instantiate the object Random generator = new Random(); // Declare several int variables to hold the generated numbers int num1, num2, num3, middle, last; // The first three numbers in the phone number must be digits 0-7 (no 8s or 9s) num1 = generator.nextInt(8); num2 = generator.nextInt(8); num3 = generator.nextInt(8); // Middle number cannot be greater than 742. In order to ensure that there // are three digits, set a minimum value of 100. Generate a value between // 0 and 642, then add 100 to shift the range middle = generator.nextInt(643) + 100; // No restrictions on the last 4 digits. However, we take a slightly different // approach to making sure that there are 4 digits. We generate a number between // 0 and 9999, then use the DecimalFormat class with a pattern of 4 0s to make // sure that leading zeros are included. last = generator.nextInt(10000); DecimalFormat fmt = new DecimalFormat("0000"); // Concatenating all of the generated values and displaying the phone number System.out.println("Phone number:" + num1 + num2 + num3 + "-" + middle + "-" + fmt.format(last)); } }