import java.util.*; import java.io.*; /* * This program randomizes a list of names by reading them * all into an array, then repeatedly selecting two slots in * the array at random to swap. If done enough time, this will * "shuffle" the array of names, randomizing their order. This * version is a little better composed, in some respects, in that * the operations of reading the data, randomizing the data, and * printing the data are all separated into their own methods. */ public class RandomDraw3 { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("names.txt")); int numStudents = input.nextInt(); input.nextLine(); // consumer '\n' character from file String [] names = new String[numStudents]; names = readNames(input, names); randomize(names); printNames(names); } //----------------------------------------------- // Output the list of names public static void printNames(String [] names) { for (int i = 0; i < names.length; i++) { System.out.println((i + 1) + ": " + names[i]); } } //----------------------------------------------- // Assign names to array slots in order they are read public static String[] readNames(Scanner input, String[] names) { for (int i = 0; i < names.length; i++) { // do this for all the slots in the array names[i] = input.nextLine(); } return names; } //----------------------------------------------- // Rearrange names in array randomly public static void randomize(String[] names) { Random r = new Random(); String aName; int rNum1, rNum2; for (int i = 0; i < 1000; i++) { // do this 1000 times, which should be enough rNum1 = r.nextInt(names.length); // to shuffle the order of names rNum2 = r.nextInt(names.length); aName = names[rNum1]; // swap the two values in the array names[rNum1] = names[rNum2]; names[rNum2] = aName; } } }