【发布时间】:2013-10-25 04:06:27
【问题描述】:
我正在尝试用 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);
}
}
【问题讨论】:
-
既然你的代码不能编译,你怎么知道它不起作用?它没有,但你真的尝试过吗?如果有,请解释问题所在(除了重复声明)。