Words and lines counter from user input for Java

ttazo :

I have done this code, it prints correctly the total number of lines but for the total number of words it always prints total of 1 word. Can someone help me please, Thanks!

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




}
Peter Lustig :

This looks rather complicated to me.

You can just save each line in an ArrayList and accumulate the words in a variable. Something like this:

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();

You should also not forget to call the close() method o the Scanner to avoid a resource leak

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12527&siteId=1