Question

I am trying to write a method that prompts the user to enter a file that stores each word to then count the frequency of the words.

The thing is that I want to use an array with a fixed size of 1000 for this method. I already declared an array of strings - String [] words = new String [1000] - within the class; however, I am not sure how to integrate it to this method in order to hold each word of the file. Any comments will be greatly appreciated!

This is what I have so far:

public static void inputFile() throws Exception
{
        java.io.File file = new java.io.File("123.txt");      
        try 
        {
            Scanner input = new Scanner(file);   
            while (input.hasNextLine()) 
            {
                String list = input.next();
                System.out.println(list);
            }
            input.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }


}
Was it helpful?

Solution

You don't need to save the content of the file into an Object. By looking at the JavaDocs, you can see that the methods of Scanner support regex.

Just read and search:

File file = new File("file.txt");

Scanner scanner = null;
try
{
    scanner = new Scanner(file);
}
catch (FileNotFoundException e){}

int i = 0;
while(scanner.hasNext("word"))
{
    scanner.next("word");
    i++;
}

System.out.println(i +" occurances of the word 'word'");

OTHER TIPS

An array is the wrong structure for this. You want a HashMap that will hold the current count for each word. You get the current count for a word, change null to 0, then add 1 and put it back in the map. You can prune it past 1000 as you like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top