Java 计算输入文件中字符的出现次数

Java 计算输入文件中字符的出现次数,java,Java,我的程序会提示用户输入特定的字母和文件名,然后在输入文件中打印出参数字母的出现次数 我写的代码: public class CharCount { public static void main(String[] args) { Scanner inp= new Scanner(System.in); String str; char ch; int count=0; System.out.println

我的程序会提示用户输入特定的字母和文件名,然后在输入文件中打印出参数字母的出现次数

我写的代码:

public class CharCount {
    public static void main(String[] args)  {
        Scanner inp= new Scanner(System.in);
        String str;
        char ch;
        int count=0;

        System.out.println("Enter a letter: ");
        str=inp.nextLine();
        while(str.length()>0)
        {
            ch=str.charAt(0);
            int i=0;

            while (i < str.length() && str.charAt(i) == ch)
            {
                count++;
                i++;
            }
            str = str.substring(count);
            System.out.println(ch + " appears " + count + " in" );
        }
    }
}
但我应该得到这个输出

Enter a letter:
e appears 1 in
Enter a letter: Enter a filename: e appears 58 times in input.txt
任何帮助/建议都很好:)

您可以使用regex

进口:

import java.util.regex.*;
使用前:

String input = "abcaa a";
String letter = "a";
Pattern p = Pattern.compile(letter, Pattern.CASE_INSENSITIVE + Pattern.MULTILINE);
Matcher m = p.matcher(input);

int i = 0;
while(m.find()){
  i++;
}
System.out.println(i); // 4 = # of occurrences of "a". 

使用Java8,您可以依靠流为您完成工作

String sampleText = "Lorem ipsum";
Character letter = 'e';
long count = sampleText.chars().filter(c -> c == letter).count();
System.out.println(count);

让我们开始帮助:

   // Ask letter:
   System.out.println("Enter a letter: ");
   String str = inp.nextLine();
   while (str.isEmpty()) {
       System.out.println("Enter a letter:");
       str = inp.nextLine();
   }
   char letter = str.charAt(0);

   // Ask file name:
   System.out.println("Enter file name:");
   String fileName = inp.nextLine();
   while (fileName.isEmpty()) {
       System.out.println("Enter file name:");
       fileName = tnp.nextLine();
   }

   // Process file:
   //Scanner textInp = new Scanner(new File(fileName)); // Either old style
   Scanner textInp = new Scanner(Paths.get(fileName)); // Or new style
   while (textInp.hasNextLine()) {
       String line = textInp.nextLine();
       ...
   }

你在代码中的什么地方输入文件名?很难描述这种方法,但是试着写更多的字母(不同的字母,而不仅仅是重复一个字母)然后享受。不同字母的计数将不断增加,然后它很可能会随着子字符串方法中的StringIndexOutOfBoundsException而消失。有趣。我如何添加输入文件?像这样吗?inputStream=新扫描仪(新文件(文件名));当我使用它的时候,我需要导入什么吗?@ross.c我对代码做了一些小的修改,并为导入添加了一行。你真是太好了。我建议问题的作者尝试一些初学者教程,而不是为他编写代码。是的,这应该给他一个好的开始。顺便说一句,我还没有多次使用
do-while
,但是你的代码看起来就像是完美的例子-尝试使用
do{…}while(str.isEmpty())
@Vlasec-Yes,但是我试着用OP已经使用过的概念来回答-直到那时,答案都是从java 8流到其他任何东西。给罗斯的主意。