我输出的单词和char的数量一直给我零.如果有人能帮助我在我的代码中找到错误的错误.星星包围的代码是我们老师给出的代码,我们需要将它放在我们的程序中.
谢谢!
**我们的老师告诉我们不要使用缓冲方法.此外,如果我更改lineNum方法,它仍会覆盖其他方法吗?部分任务是在我们的程序中使用至少两种方法****
**我根据每个人的建议编辑了我的代码**现在正在打印正确的数字!我怎样才能在其中实现我的两种方法?一个建议是我为wordCount方法使用for循环. 我还需要帮助计算段落数量 一个很好的起点?
import java.util.*;
import java.io.*;
public class WordStats1 {
public static void main(String[] args) {
try {
Scanner input = new Scanner(new FileReader("data.txt"));
//int totalLines = lineNum(input);
//int wordCount = wordCount(input);
//int countChar = countChar(input);
PrintWriter output = new PrintWriter(new FileOutputStream(
"newfile.txt"));
int lineNum = 0;
int wordCount = 1;
int charCount = 0;
while (input.hasNextLine()) {
String line;
line = input.nextLine();
//output.println(lineNum + ": " + line);
lineNum++;
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordCount ++;
}
}
charCount += (line.length());
}
System.out.println(lineNum);
System.out.println(wordCount);
System.out.println(charCount);
input.close();
output.close();
System.out.print("File written.");
}
catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
Run Code Online (Sandbox Code Playgroud)
}}
问题是,一旦你打电话lineNum(),你就在文件的末尾.当wordCount()和countChar()调用时hasNextLine(),返回false并且函数返回零.
有关如何回放a的一些想法Scanner,请参阅Java Scanner"回放".