Java用户输入的字和行计数器
我已经完成了这段代码,它正确地打印了总行数,但对于总字数,它总是打印1个字。谁能帮帮我,谢谢
import java.util.*;
public class LineAndWordCounter{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String line = scan.next();
linesCounter(scan);
wordsCounter(new Scanner(line) );
}
}
public static void linesCounter(Scanner linesInput){
int lines = 0;
while(linesInput.hasNextLine()){
lines++;
linesInput.nextLine();
}
System.out.println("lines: "+lines);
}
public static void wordsCounter(Scanner wordInput){
int words = 0;
while(wordInput.hasNext()){
words++;
wordInput.next();
}
System.out.println("Words: "+words);
}
}
# 1 楼答案
返回下一个“单词”
如果你用一个单词创建一个新的^{,它只会看到一个单词
这将发生在
# 2 楼答案
这在我看来相当复杂
只需将每一行保存在ArrayList中,并将单词累积到变量中即可。 比如:
您也不应该忘记调用
close()
方法来避免资源泄漏