我正在尝试在 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);
}
}