Forrest
Forrest

Reputation: 157

How to see how many times words from string array are present in a text file

So I want to scan a text file and find out the total amount of times that words in my array are used in that text file.

Using my code, I am only able to find out how many times the the word at position zero in my array is found in the text file. I want the total number of all the words in my array.

String[] arr = {"hello", "test", "example"};

File file = new File(example.txt);
int wordCount = 0;
Scanner scan = new Scanner(file);

for(int i = 0; i<arr.length; i++){
   while (scan.hasNext()) {
   if (scan.next().equals(arr[i])){
          wordCount++;
        }
 }
}
System.out.println(wordCount);

The example.txt would be as below:

  hello hello hi okay test hello example test
  this is a test hello example

There for, the desired result I would like would for wordCount = 9

instead, wordCount for my above code is equal to 4 (the amount of hello is stated in the text file)

Upvotes: 1

Views: 82

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347314

Scan the line from the file, then scan the arr for matches...

try (Scanner scan = new Scanner(file)) {
    while (scan.hasNext()) {
        String next = scan.next()
        for(int i = 0; i<arr.length; i++){
            if (next.equals(arr[i])){
              wordCount++;
            }
        }
    }
}

Upvotes: 3

Nameless
Nameless

Reputation: 523

What is happening in here is: in the first loop the end of file is reached and you are only getting the count of 'hello'. You can readjust the pointer to the start of the file at the end/beginning of each loop.


String[] arr = {"hello", "test", "example"};
File file = new File(example.txt);
int wordCount = 0;

for(int i = 0; i<arr.length; i++){
   Scanner scan = new Scanner(file);
   while (scan.hasNext()) {
   if (scan.next().equals(arr[i])){
          wordCount++;
        }
 }
}
System.out.println(wordCount);

Upvotes: 0

Related Questions