[Solved] Count number of times string appears in a file


Your program is not “stuck”, it is waiting for you to enter the “user input” (again).

You keep calling returnUserInput() inside the loop, and it calls getUserInput(), which will wait for you to type (another) string and press Enter.


As for your code, don’t declare line as a field. It should be a local variable.

For repeatedly searching for text in a line, don’t use contains() or a loop of every character of the line. Use indexOf(String str, int fromIndex).

Update

The code should be like this:

String word = returnUserInput();
this.counter = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
    for (String line; (line = reader.readLine()) != null; ) {
        for (int i = 0; (i = line.indexOf(word, i)) != -1; i += word.length()) {
            this.counter++;
        }
    }
}

4

solved Count number of times string appears in a file