Results 1 to 5 of 5
  1. #1
    Join Date
    Jul 2011
    Posts
    3
    Rep Power
    0

    Default Java Beginner: Can't Figure out Loop Array Issue.

    As a warning, yes, this is a homework problem, so if that deters you, you have been told!

    Anyway, this assignment is simply to find the most reoccurring word from a txt file. Okay, boom, I have that done. It works, but the problem is, is that it displays the word on multiple lines of output an absurd amount of times. I tried putting the print statement outside of the loop, but it won't display if I do that. My code is annotated so details should be good. I also realize that my code may be making this solution much more complicated than it has to be, but this is how I initially figured it out. The reason I'm not taking the awesome way out and using a hash map for this is because this was how we were told how it needs to be done. The part in bold is where the main loop that I am using is. I definitely appreciate any help you experts are graciously willing to provide. Thanks!
    Java Code:
    package lab10;
    
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class Main2 {
    
        public static void main(String[] args) {
    
          // Set the file name to use.  "final" means that we can't change it  
            // after setting its value.
            final String fName = "C:/Spec Project!/New Labs/input.txt";
    
            // "Try", because the file might be found and we want to display 
            //  nice error messages to the user.*/
            try {
                // Get an array of words from the file, using an array of size 100
                // NOTE:  The array is *created* in the method and it's reference is
                // returned.
                String[] words = getWordsFromFile(fName, 1349);
    
                // Demonstrate the reading and sorting of the array.  If the line 
                // above generated an exception, we would never get here!
                sort(words);
                System.out.println();
    
                //Display most frequent word.
                linearSearch(words);
    
            } catch (FileNotFoundException ex) {
                System.out.println("Sorry could not find file: " + fName);
                System.out.println("Java says the error message is: " + ex.getMessage());
            }
    
            System.out.println();
            System.out.println("DONE!");
        }
    
        //This remains unchanged.
        static void sort(String[] strings) {
            for (int j = 0; j < strings.length; j++) {
                for (int i = 0; i < strings.length; i++) {
                    if (strings[i].compareTo(strings[j]) > 0) {
                        swap(strings, i, j);
                    }
                }
            }
        }
    
        //This remains unchanged.
        static void swap(String[] strings, int firstInx, int lastInx) {
            String temp = strings[firstInx];
            strings[firstInx] = strings[lastInx];
            strings[lastInx] = temp;
        }
    
        //This has been changed.
        static String[] getWordsFromFile(String fileName, int size) throws FileNotFoundException {
            // Create a new array of the desired size
            String[] words = new String[size];
    
            // Create a scanner for reading the file
            File inFile = new File(fileName);
            Scanner inScan = new Scanner(inFile);
    
            // Modified to read the next word, instead of the next line.
            for (int idx = 0; inScan.hasNextLine() && idx < words.length; idx++) {
                String line = inScan.next(); //Insted of inScan.nextLine();
                words[idx] = line;
            }
            inScan.close();
            return words;
        }
    
        [B]//This has been changed.
        static int linearSearch(String[] stringArray) {
            int Counter = 1; //This is the counter that counts a single word's frequency, then resets after it gets to another word.
            int PlaceHolder = Counter; //This saves that unique "Counter" value and moves on, resetting itself.
            int i = 0; //Generic "i".
            
            String StringHold = stringArray[i]; //Holds on that unique string. Much like the PlaceHolder, but with a string instead.
            System.out.println(PlaceHolder);
            
            //A highly modified version of the linear search.
            //It gives us the result we want, sort of.
            for (i = 0; i < stringArray.length; i++) {
    
                //Creates a counter for each word that occurs uniquely
                if (stringArray[i].equals(stringArray[i + 1])) {
                    Counter++;
                    
                    //Resets and goes to a different word after conditions are met
                    // and then saves the variables.
                    if (Counter > PlaceHolder) {
                                PlaceHolder = Counter;
                                StringHold = stringArray[i];
                    }
                   // The continue statement prevents the numbers from counting up to the next number.
                   // If removed, it would display 55, and then count all the way up to 83, instead of
                   // just jumping to 83.
                    continue;
                } else {
                        Counter = 1;
                }
            }
    //The System.out.println command will not work down here, for unknown reasons.
            System.out.println("Here's proof to back up the above statement.");
            
            return PlaceHolder; //Still not sure if this does anything, but required for the method to work.
        }
    }[/B]
    //Additional Notes
    /* There does not seem to be an obvious or clear correlation between
     * how many occurrences of a word there is and how many times it is displayed
     * as output. My original guess was that it displayed the particular word as
     * many times as there were instances of it, but I have calculated this and I
     * have not found any clear distinction. It is listed as Occurrences - Display Lines:
     * 
     * "&":      1 - 6
     * "Acts":   2 - 13
     * "Assent": 4 - 35
     * "For":    9 - 19
     * "He":     18 - 120
     * "And":    55 - 256
     * "Of":     83 - 192
     */
    Last edited by CMDR Reservoir; 07-19-2011 at 02:40 AM.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    the problem is, is that it displays the word on multiple lines of output
    Perhaps I'm missing something - but I don't see where that code is outputting the most frequent word.

    I would be a good idea to format the code: put [code] at the start of the code and [/code] at the end. You can edit your post to do this, but you will have to reinsert any indenting.

    -----

    Looking more closely (than a search for "println"!) a couple of things strike me: you should use Java code conventions and start variables with a lower case letter. Also it would be good to say what happens when you run that code. If there are runtime error messages post the messages in their entirety and say to which lines of your code they refer.
    Last edited by pbrockway2; 07-19-2011 at 02:38 AM.

  3. #3
    Join Date
    Jul 2011
    Posts
    3
    Rep Power
    0

    Default

    There we go! Much nicer! Unfortunately, this is not of my formatting. It is a heavy modification of my professors file that he distributed to the entire class to use. This line of code is responsible for displaying it:

    Java Code:
    String[] words = getWordsFromFile(fName, 1349);
    
                // Demonstrate the reading and sorting of the array.  If the line 
                // above generated an exception, we would never get here!
                sort(words);
                System.out.println();
    
                //Display most frequent word.
                linearSearch(words);

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    Thanks for the formatting.

    Still I have problems with your statement that "it displays the word on multiple lines of output". There are seven println() statements: two take no argument (ie print a new line), one prints an integer value and the rest print String literals (messages). None of them print a word from the file. If you are seeing such words (printed multiple times or not) then you are not looking at output from the same code that you posted.

    Secondly, do you see a runtime exception? If so, what is it? If not, then, again, I fear that you are not looking at the behaviour of the code that you posted.

  5. #5
    Join Date
    Jul 2011
    Posts
    3
    Rep Power
    0

    Default

    I accidentally posted the wrong code part! My sincere apologies. This is the method used for the main operation:

    Java Code:
    static int linearSearch(String[] stringArray) {
            int Counter = 1; //This is the counter that counts a single word's frequency, then resets after it gets to another word.
            int PlaceHolder = Counter; //This saves that unique "Counter" value and moves on, resetting itself.
            int i = 0; //Generic "i".
            
            String StringHold = stringArray[i]; //Holds on that unique string. Much like the PlaceHolder, but with a string instead.
            System.out.println(PlaceHolder);
            
            //A highly modified version of the linear search.
            //It gives us the result we want, sort of.
            for (i = 0; i < stringArray.length; i++) {
    
                //Creates a counter for each word that occurs uniquely
                if (stringArray[i].equals(stringArray[i + 1])) {
                    Counter++;
                    
                    //Resets and goes to a different word after conditions are met
                    // and then saves the variables.
                    if (Counter > PlaceHolder) {
                                PlaceHolder = Counter;
                                StringHold = stringArray[i];
                    }
                   // The continue statement prevents the numbers from counting up to the next number.
                   // If removed, it would display 55, and then count all the way up to 83, instead of
                   // just jumping to 83.
                    continue;
                } else {
                        Counter = 1;
                }
            }
    //The System.out.println command will not work down here, for unknown reasons.
            System.out.println("Here's proof to back up the above statement.");
            
            return PlaceHolder; //Still not sure if this does anything, but required for the method to work.
        }
    }
    The one I first posted was to get the input from my file. I greatly appreciate your assistance on this project.

Similar Threads

  1. Replies: 8
    Last Post: 06-06-2011, 03:27 AM
  2. Replies: 3
    Last Post: 03-09-2011, 03:55 AM
  3. [Q] Loop issue (while loop)
    By iriscience in forum New To Java
    Replies: 9
    Last Post: 01-31-2011, 05:21 PM
  4. Beginner's Problem on Loop/If statement
    By obdi in forum New To Java
    Replies: 2
    Last Post: 07-07-2008, 02:41 AM
  5. Replies: 13
    Last Post: 07-06-2008, 10:11 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •