我从以前的建议中更新了我的代码,它只阅读我句子中的第一个单词,关于如何让它阅读整个句子的任何建议?(我必须使用 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);
}
}
输出:输入要搜索的字符 h 输入要搜索的字符串 hello how are you 在 hello 中出现 1 次 h