来自Java用户输入的单词和行计数器

问题描述 投票:0回答:2

我已经完成了此代码,它可以正确打印总行数,但是对于总单词数,它总是总可以打印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);
  }




}
java line counter word
2个回答
0
投票
scan.next()

返回下一个“单词”。

如果您从一个单词中创建一个新的Scanner,它将只会看到一个单词


0
投票

对我来说,这看起来很复杂。

您可以将每一行保存在ArrayList中,并将单词累积在变量中。像这样的东西:

List<String> arrayList = new ArrayList<>();
int words = 0;

Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
  String line = scan.nextLine();
  arrayList.add(line);
  words += line.split(" ").length;
  System.out.println("lines: " + arrayList.size());
  System.out.println("words: " + words);
}

scan.close();

您也不应忘记调用close()Scanner方法以避免资源泄漏

© www.soinside.com 2019 - 2024. All rights reserved.