我的程序应该计算用户输入的字符在字符串中出现的次数。由于某种原因,我的程序不执行 for 循环。在它打印出“输入要搜索的字符串:”之后,它不允许我输入字符串并打印出:“在‘(输入的字符串)’中出现了 0 次‘(输入的字符)’。”在新线上。我需要它能够在作为字符串输入的任意给定数量的单词中找到该字符的出现次数。我该怎么做才能使其正常运行?谢谢。
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a character for which to search: ");
char ch = input.next().charAt(0);
System.out.println("Enter the string to search: ");
String str = input.nextLine();
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i)) {
counter++;
}
}
System.out.printf("There are %d occurrences of '%s' in '%s'.", counter, ch, str);
System.out.println();
}
}
最佳答案
发生的情况是,next()
方法不会使用按 Enter 时输入的换行符。由于该字符仍在等待读取,因此 nextLine()
会消耗它。要解决此问题,您可以在 next()
调用后添加 nextLine()
:
char ch = input.next().charAt(0);
input.nextLine(); // consumes new-line character
// ...
有关更多信息,您可以阅读此 post .
关于java - 计算字符串中用户指定字符的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524687/