簡體   English   中英

Java程序可對文本文件中的行,字符和單詞進行計數

[英]Java program to count lines, char, and words from a text file

我的單詞和char數量輸出始終為零。 如果有人可以幫助我在代碼中找到錯誤,那將是很好的。 星星圍住的代碼是老師給的代碼,我們需要將其放入程序中。

謝謝!

**我們的老師告訴我們不要使用緩沖方法。 另外,如果我更改lineNum方法,它將仍然覆蓋其他方法嗎? 部分工作是在我們的程序中至少使用兩種方法****

**我根據大家的建議編輯了代碼**現在可以打印正確的數字! 如何在其中實現我的兩個方法? 有人建議我將for循環用於wordCount方法。 我還需要幫助計算段落數一個好的起點?

import java.util.*;
import java.io.*;

public class WordStats1 {

public static void main(String[] args) {
    try {

        Scanner input = new Scanner(new FileReader("data.txt"));
        //int totalLines = lineNum(input);
        //int wordCount = wordCount(input); 
        //int countChar = countChar(input);


        PrintWriter output = new PrintWriter(new FileOutputStream(
                "newfile.txt"));

        int lineNum = 0;
        int wordCount = 1;
        int charCount = 0; 

        while (input.hasNextLine()) {
            String line;
            line = input.nextLine();

            //output.println(lineNum + ": " + line);

            lineNum++;

            String str [] = line.split((" "));
              for ( int i = 0; i <str.length ; i ++) {
                if (str [i].length() > 0) {
                  wordCount ++; 
                }
              }
              charCount += (line.length());

        }

        System.out.println(lineNum);
        System.out.println(wordCount); 
        System.out.println(charCount); 
        input.close();
        output.close();

        System.out.print("File written.");

    }

    catch (FileNotFoundException e) {
        System.out.println("There was an error opening one of the files.");
    }

}}

問題是,一旦您調用lineNum() ,您就位於文件的末尾。 wordCount()countChar()調用hasNextLine() ,此方法返回false ,函數返回零。

有關如何倒帶Scanner一些想法,請參閱Java掃描器“倒帶”

您需要在一個循環內完成行數,字數和字符數的計算。 通過具有3個函數,對lineNum的第一個函數調用將在掃描程序對象上進行迭代,然后其他兩個函數調用將返回0,因為掃描程序對象已經讀取了文件,並且文件的末尾沒有任何剩余內容。讀。

我建議您編輯您的老師代碼,尤其是while循環。 刪除3個函數和相應的函數調用,並讓程序在main()函數內的循環內進行所有計數。

int lineCount = 0;
int wordCount = 0;
int charCount = 0;
while (input.hasNextLine()) {
  // read a line from the input file
  String line = input.nextLine();

  // increment line count
  lineCount++;

  // split line into words and increment word count
  String str [] = line.split((" "));
  for ( int i = 0; i <str.length ; i ++) {
    if (str [i].length() > 0) {
      wordCount ++; 
    }
  }

  // increment char count
  charCount += (line.length());
}

編輯

鑒於您已經說過需要使用2種方法,以下是我的建議:

將上面的單詞計數代碼(for循環)移至其自身的函數中,它接受String參數(當前行)並返回整數。 您可以繼續從循環內部調用它。

wordCount += countWordsInString(line);

lineNum()方法本質上是“消耗”文件,因此input.hasNextLine()在wordCount()和countChar()方法中始終返回false,因此在這兩種情況下都為零。

將這三種方法合並在一個超級計數器中,然后一次處理文件,或者將文件加載到某個臨時變量(例如字符串)中,然后將其傳遞給這三種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM