Java 计算字符串中用户指定字符的出现次数

Java 计算字符串中用户指定字符的出现次数,java,string,for-loop,character,Java,String,For Loop,Character,我的程序应该计算用户输入的字符在字符串中出现的次数。由于某些原因,我的程序不执行For循环。就在它打印出“输入要搜索的字符串:”之后,它不允许我输入字符串,而是在新行上打印出:“有0次出现“(输入的字符)”in“(输入的字符串)”。我需要它能够找到任何给定数量的单词作为字符串输入的字符出现。我该怎么做才能使它正常工作?谢谢 import java.util.Scanner; public class CountCharacters { public static void main(

我的程序应该计算用户输入的字符在字符串中出现的次数。由于某些原因,我的程序不执行For循环。就在它打印出“输入要搜索的字符串:”之后,它不允许我输入字符串,而是在新行上打印出:“有0次出现“(输入的字符)”in“(输入的字符串)”。我需要它能够找到任何给定数量的单词作为字符串输入的字符出现。我该怎么做才能使它正常工作?谢谢

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();

    }

}
import java.util.Scanner;
公共类计数字符{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入要搜索的字符:”);
char ch=input.next().charAt(0);
System.out.println(“输入要搜索的字符串:”);
String str=input.nextLine();
int计数器=0;
对于(int i=0;i
输入您的号码后,我猜您正在按
,因此在输入字符串之前需要仔细检查一下

试一试


输入您的号码后,我猜您正在按
,因此在输入字符串之前需要仔细检查

试一试


发生的情况是,
next()
方法不使用按Enter键时输入的新行字符。由于该字符仍在等待读取,因此
nextLine()
会使用它。要解决此问题,可以在
next()
调用之后添加
nextLine()

char ch = input.next().charAt(0);
input.nextLine(); // consumes new-line character

// ...

有关更多信息,您可以阅读。

发生的情况是,
next()
方法不使用按Enter键时输入的新行字符。由于该字符仍在等待读取,因此
nextLine()
会使用它。要解决此问题,可以在
next()
调用之后添加
nextLine()

char ch = input.next().charAt(0);
input.nextLine(); // consumes new-line character

// ...

如果您有一个字符列表,您可以使用Collections.frequency();做你的工作只有一句话:)@devnull:谢谢,那应该会有帮助。@WhoAmI:我得试试!另外,如果您有一个字符列表,可以使用Collections.frequency();做你的工作只有一句话:)@devnull:谢谢,那应该会有帮助。@WhoAmI:我得试试!很好的解释。非常感谢。很好的解释。非常感谢。