I'm counting how many times the word "world" occurs in a certain file.
I've tried to ways:
1)
if (words[i].equalsIgnoreCase("world")) count++;
In this case my program does not find all the instances of "world" in the file. As there are probably words in the file that contain "world" but are not equal to it.
2)if (words[i].contains("world")) count++;
In this case the program finds too many instances of "world". Again, as there are probably words in the file that contain "world" but are not equal to it.
Just in case: when I use equals() instead of equalsIgnoreCase(), the result is the same as in #1.
What am I missing?package com.codegym.task.task19.task1907;
/*
Counting words
*/
import java.io.*;
public class Solution {
public static void main(String[] args) throws FileNotFoundException, IOException {
//• The program must read the file name from the console (use BufferedReader).
BufferedReader breader = new BufferedReader(new InputStreamReader(System.in));
String fName = breader.readLine();
//String fName = "C:\\Users\\passe\\Documents\\Input.txt";
//• The BufferedReader used for reading input from the console must be closed after use.
breader.close();
//• The program must read the file's contents
// (use the FileReader constructor that takes a String argument).
FileReader freader = new FileReader(fName);
int count = 0;
//• The file input stream (FileReader) must be closed.
BufferedReader fBreader = new BufferedReader(freader);
String line = null;
while ((line = fBreader.readLine()) != null) {
//• The program must output to the console
// the number of times the word "world" appears in the file.
String[] words = line.split("[!._,'@?//s]");
for (int i = 0; i < words.length; i++) {
if (words[i].equalsIgnoreCase("world")) count++;
}
}
freader.close();
fBreader.close();
System.out.println(count);
}
}