我正在尝试用 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);
}
}
最佳答案
我看到了几个问题。首先,您有两个同名变量。
其次,您的 if
条件检查句子的长度是否大于 0,而不是检查字符是否相等。
Scanner in = new Scanner(System.in);
char inLetter = "";
String sentence = "";
System.out.println("Enter a character for which to search");
inLetter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (inLetter == ch) {
letter++;
}
}
System.out.print(sentence.charAt(letter));
我还强烈建议验证输入(在上面的示例中没有这样做),而不是仅仅假设您从第一个输入中得到 1 个字符,在第二个输入中得到 1 个句子。
关于java - 统计字符串中某个字母出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19580911/