【问题标题】:How do I read in an input file with a scanner or buffered reader and count all the occurences of a specific character in the input file如何使用扫描仪或缓冲阅读器读取输入文件并计算输入文件中特定字符的所有出现次数
【发布时间】:2015-06-27 12:15:45
【问题描述】:

如何使用扫描仪或缓冲读取器读取文件并计算文件中的所有字母“B”?

现在我正在使用扫描仪接收文件,每次遇到“B”时我都有一个 int 来计数,还有一个 int 来计数以检查字符串中的下一个字符,但它只适用于第一行,因为当 j 达到 13 时,我得到一个越界异常(输入文件每行有 13 个字符,然后是换行符)。

while (input.hasNext() == true) {
if (input.next().charAt(j) == 'B') {
b++;
}
j++;
}

我尝试在空格上拆分,但它告诉我每次都有零个“B”,这是不正确的。

【问题讨论】:

    标签: java


    【解决方案1】:

    解决此解决方案的更简单方法是设置 Scanner 的分隔符:

    input.useDelimiter("");
    

    然后,只要下一个标记等于“B”,就增加你的计数器:

    while (input.hasNext()) {
        if (input.next().equals("B"))
            b++;
    }
    

    【讨论】:

      【解决方案2】:
      static int count;
      while(input.hasNext())
      {
      String line=input.next();
      getCount(line);
      }
      
      private static int getCount(String line)
      {
      char[] arr=line.toCharArray();
      for(int i=0;i<arr.length;i++)
      {
      if(arr[i]=='B')
      count ++;
      }
      }
      

      finally count 将会有 'B' 的总数

      【讨论】:

        【解决方案3】:

        我认为StringUtils .countMatches method 是你要找的,你可以这样使用它:

        int occurences=0;
        while(input.hasNext())
        {
           String line=input.next();
           occurences+=StringUtils.countMatches(line, "B");
        }
        System.out.println("There are "+occurences+" occurences of the character B in the file.");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多