Hi,
I'm trying to figure out how to use another class as a scanner for a text analyzer class. I've pasted the class which scans the words and the class which calls the scanner. I'm just not getting how I'm supposed to get it to feed the word into the other class and to get my loops to terminate.
package assignment05; import java.io.File; import java.io.IOException; import java.util.NoSuchElementException; import java.util.Scanner; /** * A WordScanner is very similar to the Java Scanner class. It * produces word tokens from the characters in a file. Character * groups are processed to remove spaces, symbols, and other * non-word characters. During this process, non-word character * sequences are also removed. * * Set of rules to filter the results: * * Here are the first three of my rules (applied in this order): * Rule 1: Words "Mr.", "Mrs.", and "etc." are accepted as-is. * Rule 2: Words without an a, e, i, o, u, or y are rejected. * Rule 3: Dash characters are replaced with space characters, and * sub-words are re-parsed from rule 1 above. * Rule 4: Reject websites. * Rule 5: Reject emails. * Rule 6: Accepts contractions as is; such as, "isn't", "sister's", "would've". * * The WordScanner class has a debugging mode. When switched on, * WordScanners will output their word transformations to the console. * */ public class WordScanner { // Instance variables private boolean debugModeIsOn; Scanner s; String word; String currentWord; String remainWord; int index; boolean prep = false; String tempString; /** * Creates a WordScanner on the data in the given file. * This constructor throws an exception if the specified * file is not readable. * * Debug mode is disabled by default. * * @param filename the name of a text file * @throws IOException if the file cannot be read */ public WordScanner (File filename) throws IOException { debugModeIsOn = false; // Stub - not completed yet. //Creates a scanner for the file. try { s = new Scanner(filename); while (s.hasNext()) { word = s.next().toLowerCase().trim(); System.out.println(word); nextWord(); } } catch (Exception e){} } /** * Returns true if this word scanner can produce another word, * false otherwise. * * @return true if there is another available word */ public boolean hasNextWord() { prepareNextWord(); if (currentWord == null && s.hasNext() == false) return false; return true; } /** * Returns the next available word from the file. * * @return the next available word * @throws NoSuchElementException if there are no more words */ public String nextWord() throws NoSuchElementException { prepareNextWord(); hasNextWord(); if (debugModeIsOn && !tempString.equals(word)) System.out.println (word + " -> " + currentWord); if (debugModeIsOn) System.out.println (tempString + " -> rejected as non-word"); return currentWord; } /** * Sets the debugging mode for this WordScanner. If debugging * mode is enabled, then every non-standard word transformation should * generate a message to the console. * * @param debugOn true to enable debug output, false to disable debug output */ public void setDebugMode(boolean debugOn) { debugModeIsOn = debugOn; } /** * Returns the current debugging state. * * @return true if debugging output is enabled, false otherwise */ public boolean getDebugMode() { return debugModeIsOn; } /** * This private helper method sets up the 'nextWord' instance variable * to contain the next word that should be returned when nextWord() * is called. It does this by first checking to see if there is * more parsed/transformed input to be resolved. If so, the next word * is prepared. If not, another word is read from the file and processed * according to the rules. (Words are read from the file until a valid * word is found or the end of the file is reached.) * * It should be noted that each word that is read from the file may * result in several actual words. This method insulates the nextWord() * and hasNextWord() methods from this annoying detail. It keeps track * of which words have been returned, and only reads more words from the file * if there are no pending words. */ private void prepareNextWord() { if (prep) { prep = false; return; } //Removes the dashes and hyphens from the word. while (!prep && s.hasNext()) { if (currentWord == null) { currentWord = word; } if (word.contains("-")) { index = word.indexOf('-'); currentWord = word.substring(0, index); remainWord = word.substring(index+1, word.length()); } if (word.contains("_")) { index = word.indexOf('_'); currentWord = word.substring(0, index); remainWord = word.substring(index+1, word.length());; } //Rejects websites. if (word.contains("http")||word.contains("www")) { tempString = word; //continue; } //Rejects emails if (word.contains("@")||word.contains(".com")) { tempString = word; //continue; } prep = true; //Test statements to see what is inside currentWord and remainWord. System.out.println("This is the current word " + currentWord); System.out.println("This is the remaining word " + remainWord); } } }
this is the class which calls the WordScanner class
package assignment05; import java.io.File; import java.io.IOException; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class TextAnalyzer { /** * Description: This program analyzes a text document for the following; * The total number of words in the file, * The total number of words that match the input in the file. * The average length of the words in the file. * The words that precede and follow the input word. * The number of words that have the same number of characters as the input word. * The program also checks for whitespace in the user input and will prompt the * user to re-enter input until it does not contain whitespace. * */ public static void main(String[] args) { //Brings up a dialog box for the user input. String UserWord = JOptionPane.showInputDialog(null, "Please enter a word!");; //System.out.println (UserWord); //Confirms that the user input has been put into the variable. //If the user doesn't enter input, then the program will indicate that it has terminated. if (UserWord == null) { String message01 = "You did not enter a word. Goodbye!"; JOptionPane.showMessageDialog(null, message01); return; } //If the user enters whitespace then it will continue to prompt for an actual word. while (UserWord.contains(" ")) { String message04 = "You need to enter a word. Try again."; UserWord = JOptionPane.showInputDialog(null, "You need to enter a word. Try again."); if (UserWord == null) { String message01 = "You did not enter a word. Goodbye!"; JOptionPane.showMessageDialog(null, message01); return; } } //Saves the user input into the variable, converts to lowercase, and trims off whitespace. UserWord = UserWord.toLowerCase().trim();//.replaceAll("[\\W-0-9]", ""); //System.out.println (UserWord); //Confirms the input has been standardized. //Brings up dialog box for user to select a text file. JFileChooser chooser = new JFileChooser(); int check = chooser.showOpenDialog(null); File UserFile = null; //Holds the file in this variable. //If the user selects the file, then it will be stored in the variable; otherwise, will end the program. if (check == JFileChooser.APPROVE_OPTION) UserFile = chooser.getSelectedFile(); else { String message02 = "You did not choose a file. Goodbye!"; JOptionPane.showMessageDialog(null, message02); return; } String TextWord = ""; //Holds the words as each are read from the file. int WordCount = 0; //Holds the total number of words. int SameWords = 0; //Holds the number of input words. String PreceedingWord = ""; //Holds the word that alphabetically precedes the input word. String FollowingWord = null ; //Holds the word that alphabetically follows the input word. int User_and_Text = 0, Preceeding_and_Text = 0, Following_and_Text = 0; //Holds the values for the results for the string comparisons. float WordLength = 0, AvgWordLength = 0; int UserLength = 0; try { WordScanner s = new WordScanner(UserFile); s.setDebugMode(true); while (s.hasNextWord()) { TextWord = s.nextWord();//.replaceAll("[0-9-\\W]", ""); //System.out.println (TextWord); //Test statement to confirm that it is reading the text. WordCount++; //If the input is the same as the word from the text //then will update the count that keeps track of the //number of times the input word appears in the text. if (UserWord.compareTo(TextWord) == 0) SameWords++; //These comments helped me to think of how the compareTo method works. // If result < 0, m < n m precedes n // If result == 0, m.equals(n) m and n are the same // If result > 0, m > n m follows n if (FollowingWord == null && TextWord.compareTo(UserWord)>0) FollowingWord = TextWord; if(PreceedingWord != null) Preceeding_and_Text = PreceedingWord.compareTo(TextWord); if(FollowingWord != null) Following_and_Text = FollowingWord.compareTo(TextWord); //Compares the words from the file with the variable words to find the preceeding word and the following word. User_and_Text = UserWord.compareTo(TextWord); if (User_and_Text > 0 && Preceeding_and_Text < 0) PreceedingWord = TextWord; if (User_and_Text < 0 && Following_and_Text > 0) FollowingWord = TextWord; WordLength += TextWord.length(); //Holds the value for the word length of the input. //System.out.println ("the length is " + WordLength); //Confirms that WordLength is adding the total word lengths. //System.out.println(totalWordLength); //Confirms the word length is computing. AvgWordLength = WordLength/WordCount; //Holds the value for the average word length. if (UserWord.length() == TextWord.length()) UserLength++; } //s.close(); } catch (IOException e) { String message03 = "Could not read the file. Goodbye!"; JOptionPane.showMessageDialog(null, message03); return; } //Brings up a dialog box to print the results of the program. String message = "There are " + WordCount + " words in this file." + "\n"; message += "There are " + SameWords + " match(es) of the word '" + UserWord + "'\n"; message += "There are " + UserLength + " words with the same number of characters as '" + UserWord + "'." + "\n"; message += "The average word length is " + AvgWordLength + " characters per word." + "\n"; message += "In this book the word, " + PreceedingWord + ", alphabetically precedes '" + UserWord + "'." + "\n"; if (FollowingWord == null) { message += "There are no words that follow '" + UserWord + "'." + "\n"; } else message += "In this book the word, " + FollowingWord + ", alphabetically follows '" + UserWord + "'." + "\n"; JOptionPane.showMessageDialog(null, message); } }