如何计算从文本文件中打印出来的句子?

时间:2018-02-21 15:44:43

标签: java count counter fileinputstream datainputstream

我目前有这个课程打印出包含“目标”或“目标”一词的所有句子。我想知道有没有办法计算打出多少句子?该课程读取Results.txt并打印出包含“目标”或“目标”的两个句子。如何实现一个计算句子并返回第二个的方法。

    public static void main(String args[])
    {
        try{
              // Open the file that is the first 
              // command line parameter
              FileInputStream fstream = new FileInputStream("src\\sentiment\\Results.txt");
              // Get the object of DataInputStream
              DataInputStream in = new DataInputStream(fstream);
              BufferedReader br = new BufferedReader(new InputStreamReader(in));
              String strLine;

              //Read File Line By Line
              while ((strLine = br.readLine()) != null)    
              {
                  if(strLine.contains("goal") || strLine.contains("Goal"))
                  // Print the content on the console
                  System.out.println(strLine);
              }
              //Close the input stream
              in.close();
              }

        catch (Exception e)
        {//Catch exception if any
              System.err.println("Error: " + e.getMessage());
        }
 }

1 个答案:

答案 0 :(得分:3)

如果你只想计算匹配的行数,只需增加一个计数器并在你完成后打印出来:

              // Initialize the counter
              int count = 0;

              // Read File Line By Line
              while ((strLine = br.readLine()) != null)    
              {
                  if(strLine.contains("goal") || strLine.contains("Goal")){

                      // Print the content on the console
                      System.out.println(strLine);
                      // Increment the counter
                      count++;

                  }

              }

              // Print the total
              System.out.println(count);