0
        while (scan.hasNextLine()) {
        String thisline = scan.nextLine();
        totalnumber.countthelines++; //linecount works
             for(int i = 0; i < thisline.length();i++){
                  totalnumber.charactercounter++;  //chararacter count works
                  String [] thewords = thisline.split (" ");
                  totalnumber.wordcounter = thewords.length;  //does not work
             }
        }

我无法让我的 wordcounter 工作(我已经能够计算字符和行数)。我尝试了许多不同的方法来让它工作,但它总是只计算读入文件最后一行的单词。关于如何让它读取每一行而不是最后一行的任何建议?谢谢

4

3 回答 3

2

出色地 :

totalnumber.wordcounter += thewords.length

应该够了!

你只是忘了添加字数......所以整个代码是:

while (scan.hasNextLine()) {
    String thisline = scan.nextLine();
    totalnumber.countthelines++; //linecount works
    totalnumber.charactercounter+=thisline.length();  //chararacter count works
    String [] thewords = thisline.split (" ");
    totalnumber.wordcounter += thewords.length; 
    }

(对多次编辑感到抱歉。有时,它是如此明显......;)

于 2013-01-21T23:39:25.143 回答
1

你需要:

String [] thewords = thisline.split (" ");
totalnumber.wordcounter += thewords.length;

在循环之外迭代字符。请注意,+=而不是=.

于 2013-01-21T23:39:43.033 回答
0
for(int i = 0; i < thisline.length(); i++) {
    totalnumber.charactercounter++;  //chararacter count works
}

String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length;  //does not work
于 2013-01-21T23:38:34.763 回答