簡體   English   中英

Java程序,用於計算文本給定文件中的行,單詞和字符

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

我正在練習編寫一個程序,從用戶那里獲取文本文件,並提供文本中的字符,單詞和行等數據。

我搜索並查看了相同的主題,但找不到讓我的代碼運行的方法。

public class Document{
private Scanner sc;

// Sets users input to a file name
public Document(String documentName) throws FileNotFoundException {
    File inputFile = new File(documentName);
    try {
        sc = new Scanner(inputFile);

    } catch (IOException exception) {
        System.out.println("File does not exists");
    }
}


public int getChar() {
    int Char= 0;

    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        Char += line.length() + 1;

    }
    return Char;
}

// Gets the number of words in a text
public int getWords() {
    int Words = 0;

    while (sc.hasNext()) {
        String line = sc.next();
        Words += new StringTokenizer(line, " ,").countTokens();

    }

    return Words;
}

public int getLines() {
    int Lines= 0;

    while (sc.hasNextLine()) {
        Lines++;
    }

    return Lines;
}
  }

主要方法:

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        DocStats doc = new DocStats("someText.txt");

        // outputs 1451, should be 1450
        System.out.println("Number of characters: "
            + doc.getChar()); 

        // outputs 0, should be 257
        System.out.println("Number of words: " + doc.getWords());
        // outputs 0, should be 49
        System.out.println("Number of lines: " + doc.getLines()); 

    }

}

我確切地知道為什么我得到1451而不是1451.原因是因為我在最后一句末尾沒有'\\ n'但是我的方法添加了numChars + = line.length()+ 1;

但是,我無法找到解決方法,為什么我的單詞和行為0。 *我的文本包含以下內容: , - '

畢竟,有人可以幫助我做這項工作嗎?

**到目前為止,我關心的問題是我如何獲得一些字符,如果最后一句話沒有'\\ n'元素。 我有機會用if語句解決這個問題嗎?

-謝謝!

doc.getChar()您已到達文件末尾。 所以在這個文件中沒有什么可讀的了!

您應該使用getChar/Words/Lines方法重置掃描儀,例如:

public int getChar() {
    sc = new Scanner(inputFile);
...
    // solving your problem with the last '\n'
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        if (sc.hasNextLine())
            Char += line.length() + 1;
        else
            Char += line.length();
    }
    return char;
}

請注意,行結尾並不總是\\n 它也可能是\\r\\n (特別是在windows下)!

public int getWords() {
    sc = new Scanner(inputFile);
...


public int getLines() {
    sc = new Scanner(inputFile);
...

我會使用一次掃描來計算所有3個,具有不同的計數器。 只是在每個char上循環,檢查它是否是一個新單詞等,增加計數,使用Charater.isWhiteSpace *

import java.io.*;
/**Cound lines, characters and words Assumes all non white space are words so even () is a word*/
public class ChrCounts{

    String data;
    int chrCnt;
    int lineCnt;
    int wordCnt;
    public static void main(String args[]){
        ChrCounts c = new ChrCounts();
        try{
            InputStream data = null;
            if(args == null || args.length < 1){
                data = new ByteArrayInputStream("quick brown foxes\n\r new toy\'s a fun game.\nblah blah.la la ga-ma".getBytes("utf-8"));
            }else{
                data = new BufferedInputStream( new FileInputStream(args[0]));
            }
            c.process(data);
            c.print();
        }catch(Exception e){
            System.out.println("ee " + e);
            e.printStackTrace();
        }
    }

    public void print(){
        System.out.println("line cnt " + lineCnt + "\nword cnt " + wordCnt + "\n chrs " + chrCnt);
    }

    public void process(InputStream data) throws Exception{
        int chrCnt = 0;
        int lineCnt = 0;
        int wordCnt = 0;
        boolean inWord = false;
        boolean inNewline = false;
        //char prev = ' ';
        while(data.available() > 0){
            int j = data.read();
            if(j < 0)break;
            chrCnt++;
            final char c = (char)j;
            //prev = c;
            if(c == '\n' || c == '\r'){
                chrCnt--;//some editors do not count line seperators as new lines
                inWord = false;
                if(!inNewline){
                    inNewline = true;
                    lineCnt++;
                }else{
                    //chrCnt--;//some editors dont count adjaccent line seps as characters
                }
            }else{
                inNewline = false;
                if(Character.isWhitespace(c)){
                    inWord = false;
                }else{
                    if(!inWord){
                        inWord = true;
                        wordCnt++;
                    }
                }
            }
        }
        //we had some data and last char was not in new line, count last line
        if(chrCnt > 0 && !inNewline){
            lineCnt++;
        }
        this.chrCnt = chrCnt;
        this.lineCnt = lineCnt;
        this.wordCnt = wordCnt;
    }
}

暫無
暫無

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

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