Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

COSC 1010 Word Scrambler HELP!! Here are the directions for the WordSet class th

ID: 3829682 • Letter: C

Question

COSC 1010 Word Scrambler HELP!!

Here are the directions for the WordSet class that we need to write

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;

import java.util.HashSet;
import java.util.ArrayList;


/**
*
* @author Derek Green, modified by Allyson Anderson
* @version 1.2, Nov 17, 2008
* Some specification changes by William Smith 6/7/2012
*/
public class WordSet
{
private ArrayList<String> easy;
private ArrayList<String> medium;
private ArrayList<String> hard;


/**
* Constructs a WordSet object.
* The constructor takes a single String parameter
* which is the name of the file to read the words from.
* The file is read, line by line.
* Each line is broken up into an array of words.
* The words from the array are stored in a HashSet.
* The words in the HashSet are then
* sorted into 3 Arraylists depending
* on the length of the word.
*
* @param fileName
*/
public WordSet(String fileName) throws FileNotFoundException, IOException
{
  
  
  
//1.) Finish writing the constructor for WordSet.
// The constructor takes a single String parameter
// which is the name of the file to read the words from.
//2.) Instantiate the 3 fields.
//3.) Create a FileReader object.
//4.) Create a BufferedReader object.
//5.) Create a HashSet of Strings.
//6.) Read the file line by line. As long as the line is not null, do the following:
// 6a.) For each line you will need to trim any leading or trailing white space
// and convert it to lower case (use the trim() and toLowerCase() methods of
// the String class).
// 6b.) Use the split() method of the String class to split the line into an array of
// words. The split() method will take a single parameter ("[ -:;.,?]")
// which is a regular expression containing the list of characters to split the line on.
// Don't forget the single space!
// 6c.) Store all of words from the word array in the HashSet.
//
// 6d.) Close the file you are reading from.
//
//7.) Now iterate through the HashSet.
// Place each word from the HashSet into the proper ArrayList.
// Words with lengths < 2 should be ignored and skipped over.
// Words with lengths from 2-4 characters go into the easy list.
// Words with lengths from 5-8 characters go into the medium list.
// Words with lengths above 8 characters go into the hard list.
//
// Also: Your code should handle any run time exceptions that are not already being handled
// by the "throws" command. A simple System.out.println error message will be adequate
// to indicate that an error has occurred.

}
  
/**
* Gets a word from one of the 3 ArrayLists, depending
* on the difficulty level parameter.
* @param difficultyLevel 1 = easy, 2 = medium, 3 = hard
* @return word from the word set
*/
public String getWord(int difficultyLevel)
{
String word = "";
//This method selects a word from one of the 3 ArrayLists.
//The method takes one integer parameter and uses that int to
//decide which ArrayList to select a word from.
//It then selects a single word at random from the chosen
//ArrayList and returns it.
//NOTE: If the difficultyLevel is invalid, return a word
//from the hard list. This should make the coding a
//little bit easier.
return word;

}
  
}

Here are the other two filds in this class if needed:

WordScrambler Class

import java.io.IOException;
import java.io.FileNotFoundException;

/**
* A word scramble game with 3 difficulty levels.
*
* @author Derek Green, modifications by Allyson Anderson
* @version 1.2, November 2008
*/
public class WordScrambler
{
private String word;
private String scrambledWord;
private WordSet wordSet;
  
/**
* Constructs a new game with a newly scrambled word of the proper difficulty.
*
* @param level difficulty level ranges from 1-3
* @param fileName name of file with words
*/
public WordScrambler(int level, String fileName) throws FileNotFoundException, IOException
{
wordSet = new WordSet(fileName);
changeWord(level);
}
  
/**
* Gets a new word from the wordSet, and scrambles it.
*/
public void changeWord(int level)
{
word = wordSet.getWord(level);
scramble();
}
  
/**
* Scrambles the randomly chosen word and stores it in the "scramble" field.
*/
private void scramble()
{
if(word.length() > 1)
{
char[] letters = word.toCharArray();
char[] scrambledLetters;
boolean done = false;
int index;
  
do
{
scrambledLetters = new char[letters.length];
for(int i = 0; i < letters.length; i++)
{   
while(!done)
{
index = (int)(Math.random() * scrambledLetters.length);
if(scrambledLetters[index] == 0)//if no letter yet
{
scrambledLetters[index] = letters[i];
done = true;
}
}
done = false;
}
scrambledWord = String.valueOf(scrambledLetters);
}
while(scrambledWord.equals(word));//make sure it's scrambled some
}
}

/**
* Gets the scrambled word.
* @return The scrambled word.
*/
public String getScrambledWord()
{
return scrambledWord;
}
  
/**
* Gets the un-scrambled word.
* @return The unscrambled word.
*/
public String getWord()
{
return word;
}
}

Driver Class:

import javax.swing.JOptionPane;
import java.io.IOException;
import java.io.FileNotFoundException;

/**
* A Word Scrambler game. Displays random words with the letters scrambled for the
* user to guess.
*
* @author Derek Green, modifications by Allyson Anderson
* @version 1.2, November 2008
*/
public class Driver
{
private static final String TITLE = "Word Scrambler";
private static final String GET_NAME = "Please enter your name:";
private static final String GET_PLAYAGAIN = "Play again? (yes/no)?";
private static final String GET_LEVEL = "Please enter the difficulty level (1-3):";

private static final String WINNER_MSG = "You guessed it!";
private static final String LOSER_MSG = "Wrong!, Please try again.";
  
/**
* Drives the word scramble game.
*/
public static void main(String[] args)
{
String name; // player's name
String file; // name of file containing words
boolean guessed = false; // false until the word is correctly guessed
boolean done = false; // false until the player decides to end the game
String input; // holds Strings returned from showInputDialog()
String output; // used to build up Strings for display
WordScrambler game; // a single game
int level = 0; // the desired difficulty level
  
input = JOptionPane.showInputDialog(null, GET_NAME, TITLE, JOptionPane.QUESTION_MESSAGE);
testForCancel(input);
name = input;
  
input = JOptionPane.showInputDialog(null, GET_LEVEL, TITLE, JOptionPane.QUESTION_MESSAGE);
testForCancel(input);
level = Integer.parseInt(input);
  
input = JOptionPane.showInputDialog(null, "Please enter the word file name.", TITLE, JOptionPane.QUESTION_MESSAGE);
testForCancel(input);
file = input;
  
try
{
game = new WordScrambler(level, file);
  
while(!done)
{
guessed = false;
game.changeWord(level);
output = "Unscramble the word " + game.getScrambledWord();
  
while(!guessed)
{
input = JOptionPane.showInputDialog(null, output, TITLE, JOptionPane.QUESTION_MESSAGE);
testForCancel(input);
if(input.equalsIgnoreCase(game.getWord()))
{
JOptionPane.showMessageDialog(null, WINNER_MSG, TITLE, JOptionPane.INFORMATION_MESSAGE);
guessed = true;
}
else
{
JOptionPane.showMessageDialog(null,LOSER_MSG, TITLE, JOptionPane.ERROR_MESSAGE);
}
}
input = JOptionPane.showInputDialog(null, GET_PLAYAGAIN, TITLE, JOptionPane.QUESTION_MESSAGE);
testForCancel(input);
if(!input.equalsIgnoreCase("yes"))
{
done = true;
}
}
System.exit(0);
}
  
catch(FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "File does not exist.", TITLE, JOptionPane.ERROR_MESSAGE);
e.printStackTrace(System.out);
System.exit(0);
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null, "Error in opening file.", TITLE, JOptionPane.ERROR_MESSAGE);
e.printStackTrace(System.out);
System.exit(0);
}
}

/**
* Tests if the user clicked the "cancel" button and if so exits the program.
*/
private static void testForCancel(String x)
{
if(x == null)
{
System.exit(0);
}
}
  
}

Explanation / Answer

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Random;
import java.util.ArrayList;

/**
*
* @author Derek Green, modified by Allyson Anderson
* @version 1.2, Nov 17, 2008
* Some specification changes by William Smith 6/7/2012
*/
public class WordSet
{
   private ArrayList<String> easy;
   private ArrayList<String> medium;
   private ArrayList<String> hard;

   /**
   * Constructs a WordSet object.
   * The constructor takes a single String parameter
   * which is the name of the file to read the words from.
   * The file is read, line by line.
   * Each line is broken up into an array of words.
   * The words from the array are stored in a HashSet.
   * The words in the HashSet are then
   * sorted into 3 Arraylists depending
   * on the length of the word.
   *
   * @param fileName
   */
   public WordSet(String fileName) throws FileNotFoundException, IOException
   {

       //1.) Finish writing the constructor for WordSet.
       // The constructor takes a single String parameter
       // which is the name of the file to read the words from.
       //2.) Instantiate the 3 fields.
       //3.) Create a FileReader object.
       //4.) Create a BufferedReader object.
       //5.) Create a HashSet of Strings.
       //6.) Read the file line by line. As long as the line is not null, do the following:
       // 6a.) For each line you will need to trim any leading or trailing white space
       // and convert it to lower case (use the trim() and toLowerCase() methods of
       // the String class).
       // 6b.) Use the split() method of the String class to split the line into an array of
       // words. The split() method will take a single parameter ("[ -:;.,?]")
       // which is a regular expression containing the list of characters to split the line on.
       // Don't forget the single space!
       // 6c.) Store all of words from the word array in the HashSet.
       //
       // 6d.) Close the file you are reading from.
       //
       //7.) Now iterate through the HashSet.
       // Place each word from the HashSet into the proper ArrayList.
       // Words with lengths < 2 should be ignored and skipped over.
       // Words with lengths from 2-4 characters go into the easy list.
       // Words with lengths from 5-8 characters go into the medium list.
       // Words with lengths above 8 characters go into the hard list.
       //
       // Also: Your code should handle any run time exceptions that are not already being handled
       // by the "throws" command. A simple System.out.println error message will be adequate
       // to indicate that an error has occurred.

       String [] arr;
       HashSet<String> words=new HashSet<String>();
       try
       {
           FileReader in = new FileReader(fileName);
           BufferedReader br = new BufferedReader(in);
           String line;
           while ((line = br.readLine()) != null) {

               line=line.trim();
               line=line.toLowerCase();
               arr=line.split("[ -:;.,?]");

               for(int i=0;i<arr.length;i++)
               {
                   words.add(arr[i]);
               }

           }
           in.close();
           br.close();

           for (String word : words) {

               if(word.length()>=2&&word.length()<=4)
               {
                   easy.add(word);
               }
               else if(word.length()>=5&&word.length()<=8)
               {
                   medium.add(word);
               }
               else if(word.length()>8)
               {
                   hard.add(word);
               }

           }


       }
       catch(RuntimeException e)
       {
           System.out.println(e.getMessage());
       }


   }
   /**
   * Gets a word from one of the 3 ArrayLists, depending
   * on the difficulty level parameter.
   * @param difficultyLevel 1 = easy, 2 = medium, 3 = hard
   * @return word from the word set
   */
   public String getWord(int difficultyLevel)
   {
       String word = "";
       //This method selects a word from one of the 3 ArrayLists.
       //The method takes one integer parameter and uses that int to
       //decide which ArrayList to select a word from.
       //It then selects a single word at random from the chosen
       //ArrayList and returns it.
       //NOTE: If the difficultyLevel is invalid, return a word
       //from the hard list. This should make the coding a
       //little bit easier.
       Random random = new Random();

       int randomNumber =0;

       if(difficultyLevel==1)
       {
           randomNumber = random.nextInt((easy.size()-1) + 1 - 0) + 0;

           word= easy.get(randomNumber);

       }
       else if(difficultyLevel==2)
       {
           randomNumber = random.nextInt((medium.size()-1) + 1 - 0) + 0;
           word= medium.get(randomNumber);
       }
       else
       {
           randomNumber = random.nextInt((hard.size()-1) + 1 - 0) + 0;
           word=hard.get(randomNumber);
       }

       return word;
   }

}