2015-11-04 47 views
3

我正在練習編寫一個程序,該程序從用戶獲取文本文件,並在文本中提供數據(如字符,單詞和行)。用於計算文本給定文件中的行數,字數和字符數的Java程序

我已經搜索並查看了相同的主題,但無法找到使代碼運行的方法。

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語句解決這個問題?

- 謝謝!

+0

請顯示您的實際代碼。你正在調用一個方法getNumberOfCharacters,它不存在於你的代碼中,所以這甚至不會編譯,更不用說運行 – Stultuske

+0

另外:不要使用StringTokenizer。這是一個遺留類,不應該使用。使用字符串的拆分方法或正則表達式。新的StringTokenizer(行,「,」)這分裂在一個「,」,所以:「我在這裏」你不會真的包含單詞。 – Stultuske

+0

這是我的實際代碼。我稱之爲不同方法的原因是因爲我運行了很多類似的代碼,以瞭解如何修復我自己的代碼。這就是爲什麼我忘記將它改回我的方法的原因。 –

回答

2

之後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); 
... 
+0

這實際上幫助我得到了一些詞而不是零。 –

+0

它應該給你適量的行,你可能需要在你的單詞方法上工作一點;) – ParkerHalo

+0

是的,在這一點上,我得到了錯誤的字符和單詞數量。我的最後一句在最後沒有'\ n',所以我現在的算法不起作用。我想用if語句來解決它。你能提出任何可以幫助我的建議嗎? –

1

我會用一個掃描來計算所有3,用不同的計數器。只是一個循環在每個字符,檢查是否它的一個新的單詞等,增加計數,使用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; 
    } 
} 
相關問題