我试着制作一个简单的计数器来计算一个字符在字符串中出现的次数,但我做错了。当我尝试打印计数器时,它会重复多次。
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);
}
}
}
答案 0 :(得分:6)
放置
System.out.println("This string has " + counter + " " + letter);
在循环之外,你已经完成了。
答案 1 :(得分:1)
将System.out.println("This string has " + counter + " " + letter);
放在for
循环
答案 2 :(得分:0)
代码应该是......
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(“此字符串包含”+ counter +“”+ letter);