0

I wrote a program that counts the total number of occurrences of some substring in a string

But there can be many lines in the text

Now there are 3 lines in the text, and the program outputs a value for each of the lines

The code outputs 3 numbers, although I need one, which is how to fix it? another cycle?

public class OccurrencesAmount {
    public static int getOccurrencesAmount(String substring, String string) {
        substring = substring.toUpperCase();
        string = string.toUpperCase();

        int count = 0;
        int fromIndex = 0;
        int length = substring.length();

        while (true) {
            int occurrenceIndex = string.indexOf(substring, fromIndex);

            if (occurrenceIndex < 0) {
                break;
            }

            count++;
            fromIndex = occurrenceIndex + length;
        }

        return count;
    }

    public static void main(String[] args) throws FileNotFoundException {
        try (Scanner scanner = new Scanner(new FileInputStream("input.txt"))) {
            String searchLine = "о";

            while (scanner.hasNextLine()) {
                System.out.println(
                        getOccurrencesAmount(searchLine, scanner.nextLine()));
            }
        }
    }
}
Digger
  • 11
  • 4

1 Answers1

2

At the moment your program outputs for every single line.

Your method is already returning an int-value. So to get the total amount of occurences over all lines, you just need to sum them up like this:

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        String searchLine = "о";
        
        int totalOccurences = 0;
        while (scanner.hasNextLine()) {
            totalOccurences += getOccurrencesAmount(searchLine, scanner.nextLine());
        }
        
        System.out.println(totalOccurences);
    }
}
csalmhof
  • 1,820
  • 2
  • 15
  • 24