Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Spell checker using bags

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Spell checker using bags

    The program I am required to write reads in a text file and spell checks it. The program also reads in another text file that has a couple words that are correctly spelled and stores it in a "bag". Then it checks if a word is in the bag. I am to ignore case numbers the following words [a, an, the, I, and]. I have to ask the user if they want to add a word to the bag if it can't find the word in the bag.

    Problem: The below code (SpellChecker.java) won't add words to the dictionary bag in the setDictionary method.

    Question: How do I ignore case and prevent the user from adding misspelled words or proper names?

    BagInterface.java:
    /**
       An interface that describes the operations of a bag of objects.
       @author Frank M. Carrano
    */
    public interface BagInterface<T>
    {
    	/** Gets the current number of entries in this bag.
    		 @return the integer number of entries currently in this bag */
    	public int getCurrentSize();
     
    	/** Sees whether this bag is full.
    		 @return true if this bag is full, or false if not */
    	public boolean isFull();
     
    	/** Sees whether this bag is empty.
    		 @return true if this bag is empty, or false if not */
    	public boolean isEmpty();
     
    	/** Adds a new entry to this bag.
    	    @param newEntry  the object to be added as a new entry
    	    @return true if the addition is successful, or false if not */
    	public boolean add(T newEntry);
     
    	/** Removes one unspecified entry from this bag, if possible.
           @return either the removed entry, if the removal
                   was successful, or null */
    	public T remove();
     
    	/** Removes one occurrence of a given entry from this bag.
           @param anEntry  the entry to be removed
           @return true if the removal was successful, or false if not */
       public boolean remove(T anEntry);
     
    	/** Removes all entries from this bag. */
    	public void clear();
     
    	/** Counts the number of times a given entry appears in this bag.
    		 @param anEntry  the entry to be counted
    		 @return the number of times anEntry appears in this bag */
    	public int getFrequencyOf(T anEntry);
     
    	/** Tests whether this bag contains a given entry.
    		 @param anEntry  the entry to locate
    		 @return true if this bag contains anEntry, or false otherwise */
    	public boolean contains(T anEntry);
     
    	/** Retrieves all entries that are in this bag.
    		 @return a newly allocated array of all the entries in this bag */
    	public T[] toArray();

    ResizeableArrayBag.java:
    import java.util.Arrays;
    /**
       A class that implements a bag of objects by using an array.
    	The bag is never full.
       @author Frank M. Carrano
       @version 3.0
    */
    public class ResizableArrayBag<T> implements BagInterface<T>
    {
    	private T[] bag; // cannot be final due to doubling
    	private static final int DEFAULT_INITIAL_CAPACITY = 25; // initial capcity of bag 
    	private int numberOfEntries=0;
     
    	/** Creates an empty bag whose initial capacity is 25. */
    	public ResizableArrayBag() 
    	{
    		this(DEFAULT_INITIAL_CAPACITY);
    	} // end default constructor
     
    	/** Creates an empty bag having a given initial capacity.
    	    @param capacity  the integer capacity desired */
    	public ResizableArrayBag(int capacity) 
    	{
    		numberOfEntries = 0;
          // the cast is safe because the new array contains null entries
          @SuppressWarnings("unchecked")
          T[] tempBag = (T[])new Object[capacity]; // unchecked cast
          bag = tempBag;
    	} // end constructor
     
    	/** Creates a bag containing given entries.
    	    @param contents  an array of objects */
       public ResizableArrayBag(T[] contents) 
       {
          bag = Arrays.copyOf(contents, contents.length);
          numberOfEntries = contents.length;
       } // end constructor
     
    	/** Adds a new entry to this bag.
    	    @param newEntry  the object to be added as a new entry
    	    @return true if the addition is successful, or false if not */
    	public boolean add(T newEntry) 
    	{
    		ensureCapacity();
    		bag[numberOfEntries] = newEntry;
    		numberOfEntries++;
     
    		return true;
    	} // end add
     
       // Doubles the size of the array bag if it is full
    	private void ensureCapacity() 
    	{
    		if (numberOfEntries == bag.length)
             bag = Arrays.copyOf(bag, 2 * bag.length);
    	} // end ensureCapacity
     
       /** @return true; the bag is never full because the array bag is 
                   resized, as necessary */
    	public boolean isFull() 
    	{
    		return false;
    	} // end isFull
     
    	/** Retrieves all entries that are in this bag.
    	    @return a newly allocated array of all the entries in the bag */
    	public T[] toArray() 
    	{
          // the cast is safe because the new array contains null entries
          @SuppressWarnings("unchecked")
          T[] result = (T[])new Object[numberOfEntries]; // unchecked cast
     
    		for (int index = 0; index < numberOfEntries; index++) 
    		{
    			result[index] = bag[index];
    		} // end for
     
    		return result;
    	} // end toArray
     
    	/** Sees whether this bag is empty.
    	    @return true if this bag is empty, or false if not */
    	public boolean isEmpty() 
    	{
    		return numberOfEntries == 0;
    	} // end isEmpty
     
    	/** Gets the (current) capacity of this bag.
    	    @return the integer number of entries that the bag can hold */
    	public int getCapacity() 
    	{
    		return bag.length;
    	} // end getCapacity
     
    	/** Gets the number of entries currently in this bag.
    	    @return the integer number of entries currently in the bag */
    	public int getCurrentSize() 
    	{
    		return numberOfEntries;
    	} // end getCurrentSize
     
    	/** Counts the number of times a given entry appears in this bag.
    		 @param anEntry  the entry to be counted
    		 @return the number of times anEntry appears in the bag */
    	public int getFrequencyOf(T anEntry) 
    	{
    		int counter = 0;
     
    		for (int index = 0; index < numberOfEntries; index++) 
    		{
    			if (anEntry.equals(bag[index]))
    			{
    				counter++;
    			} // end if
    		} // end for
     
    		return counter;
    	} // end getFrequencyOf
     
    	/** Tests whether this bag contains a given entry.
    		 @param anEntry  the entry to locate
    		 @return true if the bag contains anEntry, or false otherwise */
    	public boolean contains(T anEntry)
    	{
    		return getIndexOf(anEntry) > -1;
    	} // end contains
     
     	// Locates a given object within the array bag.
    	// Returns the index of the object, if located,
    	// or -1 otherwise.
    	private int getIndexOf(T anEntry) 
    	{
    		int where = -1;
    		boolean found = false;
     
    		for (int index = 0; !found && (index < numberOfEntries); index++) 
    		{
    			if (anEntry.equals(bag[index]))
    			{
    				found = true;
    				where = index;
    			} // end if
    		} // end for
     
    		return where;
    	} // end getIndexOf
     
    	/** Removes all entries from this bag. */
    	public void clear() 
    	{
    		while (!isEmpty()) 
             remove();
          //    while (remove() != null) {} // Q7
    	} // end clear
     
    	/** Removes one unspecified entry from this bag.
           @return either the removed entry, if the removal
                   was successful, or null otherwise */
    	public T remove()
    	{
    		T result = removeEntry(numberOfEntries - 1);
     
    		return result;
    	} // end remove
     
    	/** Removes one occurrence of a given entry from this bag.
           @param anEntry  the entry to be removed
           @return true if the removal was successful, or null otherwise */
       public boolean remove(T anEntry) 
    	{
    		int index = getIndexOf(anEntry);
          T result = removeEntry(index);
     
    		return anEntry.equals(result);
    	} // end remove
     
       // Removes and returns the array entry at a given index.
       // If no such entry exists, returns null.
    	private T removeEntry(int givenIndex)
    	{
    		T result = null;
     
    		if (!isEmpty() && (givenIndex >= 0))
    		{
             result = bag[givenIndex]; // entry to remove
             numberOfEntries--;
             bag[givenIndex] = bag[numberOfEntries]; // replace entry to remove with last entry
             bag[numberOfEntries] = null; // remove reference to last entry
    		} // end if
     
          return result;
    	} // end removeEntry   
    } // end ResizableArrayBag

    SpellChecker.java:
    import java.util.*;
     
    public class SpellChecker
    {
    	BagInterface<String> dictionary;
    	static Scanner console = new Scanner(System.in);
     
    	public SpellChecker()
    	{
    		dictionary = new ResizableArrayBag<String>();
    	} // end default constructor
     
    	/** Initializes the dictionary of correctly spelled words. 
    	 */
    	public void setDictionary(Scanner file)
    	{
    		int numWords=0;
     
     
    			while (file.hasNextLine())
    			{
    				numWords = file.nextInt();
     
    				String word = file.nextLine();
    				dictionary.add(word);
    			} // end while
     
    			System.out.println(dictionary.getCurrentSize());
     
    			} // end setDictionary
     
    	/** Checks the spelling of a given word. 
           @param aWord  a string whose spelling is to be checked
           @return true if the given word is spelled correctly, otherwise
                   returns false */
    	public void checkSpelling(String lineOfText)
    	{
    		String[] aWord, bWord;
    		bWord = new String[50];
    		String delim = "[ .,?!()]+", yn;
    		int j=0;
     
    		aWord = lineOfText.split(delim);
     
    		for (int i = 0; i < aWord.length; i++)
    		{
    			if (!ignoreWord(aWord[i]))
    			{
    				if (!dictionary.contains(aWord[i]))
    				{
    					bWord[j] = aWord[i];
    					j++;
    				}
    			}
    		}
     
    		if (bWord == null)
    			System.out.println("No errors!");
    		else
    			{
    				System.out.println("You have the following errors:");
     
    				for (int k = 0; k < bWord.length; k++)
    				{
    					System.out.println(bWord[k]);
    					System.out.print("Would you like to add it to the dictionary? (Y/N) ");
    					yn = console.nextLine();
    					if (yn.equalsIgnoreCase("y"))
    						dictionary.add(bWord[k]);
    				}
    			}
    	} // end checkSpelling
     
    	private boolean ignoreWord(String word)
    	{
    		if (word.equalsIgnoreCase("a") || word.equalsIgnoreCase("the") || word.equalsIgnoreCase("an") || word.equalsIgnoreCase("i") || word.equalsIgnoreCase("and"))
    			return true;
    		else if (word.charAt(0) == '$')
    		{
    			if (isItNum(word))
    				return true;
    		}
    		else if (isItNum(word))
    			return true;
     
    		return false;
    	}
     
    	private boolean isItNum(String word)
    	{
    	    for (int i = 1; i < word.length(); i++) {
    	        //If we find a non-digit character we return false.
    	        if (!Character.isDigit(word.charAt(i)))
    	        return false;
    	        }
    	        return true;
    	}
    } // end SpellChecker

    TextFileOperations.java:
    //FROM APPENDIX F
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
     
     
    public class TextFileOperations
    {
    	static SpellChecker checker = new SpellChecker();
     
    	public static void main(String[] args) 
    	{
    		if (!readDictionary("dictionary.txt"))
    			 System.out.println("Dictionary File not found");
     
    		if (!readWords("words.txt"))
    			 System.out.println("Word File not found");
    	}
    	// Read dictionary file
       public static boolean readDictionary(String fileName) 
       {
          int num, count;
          boolean fileOpened;
          String line;
          try
          {
             Scanner fileData = new Scanner(new File(fileName));
     
     
             num = fileData.nextInt();
             System.out.println("The file contains the following lines:");
             for (count=1; count<=num; count++)
             {
            	 line = fileData.next();
                 System.out.println(line);
             } // end for
     
             checker.setDictionary(fileData);
     
             fileData.close();
             fileOpened = true;
          }
          catch (FileNotFoundException e)
          {
             fileOpened = false; // error opening the file
          }
     
          return fileOpened;
       } // end readDictionary
       public static boolean readWords(String fileName) 
       {
          int num, count;
          boolean fileOpened;
          String line, wText="";
          try
          {
             Scanner fileData = new Scanner(new File(fileName));
     
             System.out.println("The file contains the following lines:");
             while (fileData.hasNext())
             {
            	 line = fileData.nextLine();
            	 wText = wText + line;
                 System.out.println(line);
             } // end while
             checker.checkSpelling(wText);
             fileData.close();
             fileOpened = true;
          }
          catch (FileNotFoundException e)
          {
             fileOpened = false; // error opening the file
          }
     
          return fileOpened;
       } // end readWords
    } // end TextFileOperations


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Spell checker using bags

    How do I ignore case
    and prevent the user from adding misspelled words or proper names?
    You could change every word to the same case (upper or lower)

    I don't know how to prevent a user from entering bad data without having a super dictionary to check against.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Need switch statement for checker game (DUE TOMORROW!)
    By strengthonor in forum Loops & Control Statements
    Replies: 1
    Last Post: September 16th, 2011, 03:40 AM
  2. Magic Square Checker
    By Hypnos in forum Object Oriented Programming
    Replies: 1
    Last Post: April 3rd, 2011, 06:37 PM
  3. Password Strength Checker
    By uthuth in forum Object Oriented Programming
    Replies: 1
    Last Post: February 6th, 2010, 04:09 PM