문자열에 문자가있는 횟수를 계산하는 간단한 카운터를 만들려고 노력하고 있지만 잘못하고 있습니다. 카운터를 인쇄하려고하면 여러 번 반복됩니다.출력이 계속 반복되는 이유는 무엇입니까?
import java.util.Scanner;
public class Uppgift5 {
public static void main(String[] args) {
int counter = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("What string do you want to search: ");
String string = scanner.nextLine();
System.out.println("What letter do you want to count? ");
String letter = scanner.nextLine();
for(int i=0; i<string.length(); i++) {
if (string.charAt(i) == letter.charAt(0)){
counter++;
}
System.out.println("This string has " + counter + " " + letter);
}
}
}
+1 간단한 대답입니다. – Maroun