我正在尝试编写一个程序,该程序以类似于字处理程序的方式收集文本文件的统计信息,该程序会告诉您有多少个字符,单词和你写的线。用于统计文本文件中的字符,单词和行的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
}
}
谁能指出为什么我的代码不能正常工作,并提出任何替代的方式来解决这个问题?
在你'hasNext'与'next'一个地方。在另一种情况下,你可以使用'hasNext'和'nextLine'。在另一个例子中,你只需使用'hasNext'。你知道那些是做什么的吗? –