package Lect42Review; import javax.swing.*; // Idea: This program will select a random word from an array and it will // scramble the letters of the word. The program will show the scrambled // word to the user and keep asking the user for the original word. // // Reviews: do while, array of characters, Math.random, // instance variables, converting arrays of characters int public class Scramble { private String[] allWords = {"house", "cat", "table", "television", "newspaper", "dedication"}; private String wordToScramble; private String scrambledWord; private void scrambleWord() { // Note: uses nested loop as there is a chance the scrambled // word generated is the same as the selected word. // Probability of this is high for short words (e.g. cat) do { int wordSize = wordToScramble.length(); char[] scrambledArray = new char[wordSize]; boolean[] picked = new boolean[wordSize]; int index, currentPosition = 0; // We will repeatedly select a random character from the // word. If the character has not been previously selected, // we will use it for the next position in the scrambled // array. The alreadyPicked array will tell us whether // a selected character was already considered. do { index = (int)(Math.random() * wordSize); if (!picked[index]) { picked[index] = true; scrambledArray[currentPosition++] = wordToScramble.charAt(index); } } while (currentPosition < wordSize); // rely on String constructor that takes a character array scrambledWord = new String(scrambledArray); } while(wordToScramble.equals(scrambledWord)); } private void doUserInput() { String message = "Guess the word represented by " + scrambledWord; String guess; do { guess = JOptionPane.showInputDialog(message); } while (!guess.equals(wordToScramble)); message = "You unscrambled the word"; JOptionPane.showMessageDialog(null, message); } public Scramble() { int selectedWordIndex = (int)(Math.random() * allWords.length); wordToScramble = allWords[selectedWordIndex]; scrambleWord(); doUserInput(); System.exit(0); } public static void main(String[] args) { new Scramble(); } }