/** * Class that simulates a simple slot machine. * * @author Dave Reed * @version 9/21/06 */ public class SlotMachine { private int numSpins; // keeps track of the number of spins /** * Constructor for objects of class SlotMachine. */ public SlotMachine() { this.numSpins = 0; } /** * Simulates a spin of the slot machine. * @return a String identifying the three slot images obtained, and whether * they represent a win or loss for the player */ public String spin() { String slot1 = this.randomImage(); String slot2 = this.randomImage(); String slot3 = this.randomImage(); this.numSpins = this.numSpins + 1; if (slot1.equals(slot2) && slot2.equals(slot3)) { return slot1 + "-" + slot2 + "-" + slot3 + ": YOU WIN!"; } else { return slot1 + "-" + slot2 + "-" + slot3 + ": YOU LOSE!"; } } /** * Private helper method for randomly generating a single slot image. * This method is called by the public spin method for getting the * three slot images. * @return the random image (either "cherry", "lemon", or "bar") */ private String randomImage() { int randomNum = (int)(3*Math.random() + 1); // either 1, 2 or 3 if (randomNum == 1) { return "cherry"; } else if (randomNum == 2) { return "lemon"; } else { return "bar"; } } }