import java.io.*; import java.util.Random; /* * A class to illustrate some potentially useful ideas for the * WheelOfFortune project. */ public class WheelOfFortuneHints { /* Some instance variables. */ private Random theRandomGenerator; private boolean theLoopGoesOn; private BufferedReader theFileReader; private String oneLineFromFile; private StringBuffer theStringBuffer; private int numLines; /* * The main program creates a WheelOfFortuneHints object * and then calls instance methods on it. */ public static void main(String[] args) { /* Create an instance of the WheelOfFortuneHints class. */ WheelOfFortuneHints hinter = new WheelOfFortuneHints(); /* Now we can call the instance methods on this instance. */ hinter.initializeHints(); hinter.runHint(); /* Also we can access the instance variables of this instance. */ System.out.println("The number of lines is " + hinter.numLines); } /* * Initialize some of the instance variables of a WheelOfFortuneHints * object. Although the WheelOfFortuneHints object is not a parameter, * we have access to it implicitly because this is a non-static * instance method. */ private void initializeHints() { theRandomGenerator = new Random(5); // Seed a Random object with seed 5. try { theFileReader = new BufferedReader(new FileReader("wheel.txt")); } catch(IOException e) { System.out.println("File wheel.txt not found."); e.printStackTrace(); } } /* * This function reads each line from a file, keeps a count of the * number of lines, and prints out the line with a random character * replaced with a '*' character. */ private void runHint() { numLines = 0; theLoopGoesOn = true; try { while (theLoopGoesOn) // Note use of boolean variable to control loop. { oneLineFromFile = theFileReader.readLine(); if (oneLineFromFile == null) { theLoopGoesOn = false; // Something happened to end the loop. } else { numLines++; theStringBuffer = new StringBuffer(oneLineFromFile); System.out.println("Before:); System.out.println(theStringBuffer); replaceRandomCharacter(); System.out.println("After:"); System.out.println(theStringBuffer); } } } catch(IOException e) { System.out.println("Problem reading from file."); e.printStackTrace(); } } /* * This function replaces a character at a random position in the * StringBuffer with an '*' character. * Illustrates the setCharAt method in the StringBuffer class. */ public void replaceRandomCharacter() { int replacementPos = theRandomGenerator.nextInt(theStringBuffer.length()); theStringBuffer.setCharAt(replacementPos, '*'); } }