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
             }
        }


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

最佳答案

好 :

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;
    }


(很抱歉,多次编辑。有时候,这很明显...;)

10-07 12:16