/*******************************************
Woody Wordword likes to play Scrabble. He wants to practice
on his own, when no other players are available. His idea is
to have the computer choose a random word, then scramble up
the letters and display the result. Then he tries to guess
the original word, types his guess, and the computer tells
him whether he was correct.
********************************************/
public class MixUp
{
String[] words = {"hopeful", "unhappy", "worried", "liberty",
"general", "trigger", "napkins", "showing",
"legible", "rotated", "parsing", "fiddler"
};
public MixUp()
{
String chosen = chooseWord();
output("The mixed up letters are: \n" + mixup(chosen));
String answer = input("Your answer");
if(answer.equalsIgnoreCase(chosen))
{ output("Well done"); }
else
{ output("No, the word was " + chosen); }
}
public String chooseWord()
{
int num = (int)(Math.random()*words.length);
return words[num];
}
public String mixup(String w)
{
// take individual letters and store in an array
// swapping is much easier in an array than a String
String[] letters = new String[w.length()];
for(int x = 0; x < w.length(); x=x+1)
{
letters[x] = w.substring(x,x+1);
}
// choose two random letters and swap, repeat 10 times
for(int x = 0; x < 10; x=x+1)
{
int a = (int)(Math.random()*w.length());
int b = (int)(Math.random()*w.length());
String temp = letters[a];
letters[a] = letters[b];
letters[b] = temp;
}
// concatenate letters from array back into a String
String result = "";
for(int x = 0; x < w.length(); x = x+1)
{
result = result + letters[x];
}
return result;
}
public static void main(String[] args)
{ new MixUp(); }
public String input(String prompt)
{ return javax.swing.JOptionPane.showInputDialog(null,prompt); }
public void output(String message)
{ javax.swing.JOptionPane.showMessageDialog(null,message); }
}