2015-11-04 76 views
-3

我正在尝试编写一个程序,该程序以类似于字处理程序的方式收集文本文件的统​​计信息,该程序会告诉您有多少个字符,单词和你写的线。用于统计文本文件中的字符,单词和行的Java程序

该程序的目的是要求用户输入文件名(,使用扫描仪)并输出统计信息。

这是我到目前为止有:

public class DocStats { 
private File inputFile; 
private Scanner in; 

// Sets users input (string attribute) to a file name 
public DocStats(String string) throws FileNotFoundException { 
    try { 
     File inputFile = new File(string); 
     Scanner in = new Scanner(inputFile); 

     this.inputFile = inputFile; 
     this.in = in; 
    } catch (IOException exception) { 
     System.out.println("Could not open the file"); 
    } 
} 

// Gets the number of characters in a text 
public int getNumberOfCharacters() { 
    int numChar = 0; 

    while (in.hasNext()) { 
     String line = in.nextLine(); 
     numChar += line.length(); 
    } 

    return numChar; 
} 

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

    while (in.hasNextLine()) { 
     String line = in.nextLine(); 
     numWords += new StringTokenizer(line, " ,").countTokens(); 
    } 

    return numWords; 
} 

// Gets the number of lines in a text 
public int getNumberOfLines() { 
    int numLines = 0; 

    while (in.hasNextLine()) { 
     numLines++; 
    } 

    return numLines; 
} 

} 

我在main方法测试我下课后,我没有得到正确的输出。这里是主要的方法:

import java.io.*; 

public class Main { 

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

    System.out.println("Number of characters: " 
      + doc.getNumberOfCharacters()); // outputs 1402, instead of 1450 

    System.out.println("Number of words: " + doc.getNumberOfWords()); // outputs 
                     // 0 
                     // instead 
                     // of 
                     // 257 
    System.out.println("Number of lines: " + doc.getNumberOfLines()); // outputs 
                     // 0 
                     // instead 
                     // of 
                     // 49 
} 
} 

谁能指出为什么我的代码不能正常工作,并提出任何替代的方式来解决这个问题?

+0

在你'hasNext'与'next'一个地方。在另一种情况下,你可以使用'hasNext'和'nextLine'。在另一个例子中,你只需使用'hasNext'。你知道那些是做什么的吗? –

回答

0

您正在扫描getNumberOfCharacters()方法中的文件,这就是为什么它不为零的原因。由于扫描器位于文件末尾,其他值为0。

你需要改变你的DocStats类只有一个循环

in = new Scanner(file); 
while(in.hasNextLine()) { 
    // count the lines 
    lines++; 
    String line = in.nextLine(); 

    // chars in the line, plus one for the newline 
    chars += line.length() + 1; 

    // count words. Are there other word terminators, such as . ? ! - 
    words += new StringTokenizer(line, " ,").countTokens(); 
} 
+0

我试图运行你的代码,但是,我仍然得到错误的值。在我的.txt文件中,最后一行没有'\ n',这意味着我不能使用字符+ = line.length()+ 1;同时,我仍然得到0的字数和行数。而最后一件事,我确实有这样的元素。 ? ! - 在我的文本中 –

相关问题