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()));
}
}
}
}