gpt4 book ai didi

计算文本给定文件中的行数、单词数和字符数的 Java 程序

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:58 25 4
gpt4 key购买 nike

我正在练习编写一个从用户那里获取文本文件并提供文本中的字符、单词和行等数据的程序。

我搜索并查看了同一主题,但找不到让我的代码运行的方法。

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);
...

关于计算文本给定文件中的行数、单词数和字符数的 Java 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33516101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com