我正在尝试在Java中编写for循环来计算字符串中字母的出现次数。用户将输入要计数的字母以及要在其中搜索的字符串。这是一个非常基本的代码,我们还没有得到数组或其他许多东西。 (我知道我宣布了两封信,但是我的大脑已经死亡了)这是我迄今为止尝试过的,并且遇到了麻烦,任何帮助都会被赞赏:计算字符串中字母的出现次数
好的,我按照建议更改了代码,但现在它只是读我的第一句话吗?
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char letter;
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
count++;
}
}
System.out.printf("There are %d occurrences of %s in %s", count,
letter, sentence);
}
}
由于你的代码不会编译,你怎么知道它不起作用?它不,但你真的尝试过吗?如果你有,然后解释什么是问题(除了重复的声明)。 –