使用字符串数组的文件字数(JAVA) while(scan.hasNextLine()){ String thisline=scan.nextLine(); totalnumber.countthelines++;//行数有效 对于(int i=0;i

使用字符串数组的文件字数(JAVA) while(scan.hasNextLine()){ String thisline=scan.nextLine(); totalnumber.countthelines++;//行数有效 对于(int i=0;i,java,string,count,split,word,Java,String,Count,Split,Word,我很难让我的文字计数器工作(我已经能够计算字符和行)。我尝试了许多不同的方法使其工作,但它总是只计算读取文件最后一行中的单词。关于如何让它阅读每一行而不是最后一行,有什么建议吗? 感谢(inti=0;i

我很难让我的文字计数器工作(我已经能够计算字符和行)。我尝试了许多不同的方法使其工作,但它总是只计算读取文件最后一行中的单词。关于如何让它阅读每一行而不是最后一行,有什么建议吗? 感谢(inti=0;i
for(int i=0;i
井:

for(int i = 0; i < thisline.length(); i++) {
    totalnumber.charactercounter++;  //chararacter count works
}

String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length;  //does not work
应该够了

你只是忘了增加字数。。。 因此,entiere代码是:

totalnumber.wordcounter += thewords.length
(很抱歉进行了多次编辑。有时,这太明显了……)

嗯:

for(int i = 0; i < thisline.length(); i++) {
    totalnumber.charactercounter++;  //chararacter count works
}

String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length;  //does not work
应该够了

你只是忘了增加字数。。。 因此,entiere代码是:

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; 
    }
在循环外部迭代字符。请注意您需要的是
+=
而不是
=

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

在循环外部迭代字符。注意
+=
而不是
=

不要问问题,稍后删除代码。我已经解决了你的两个问题,这是你做的。停止不要问问题,然后删除代码。我已经解决了你的两个问题,这是你做的。停止