简体   繁体   中英

Counting words and lines using scanner Scanner (Java)

This is my first time here at stackoverflow and sometimes tells me that i will be here quite a lot of times soon xD.

I'm trying to do a pretty simple thing, counting the number of words and the number of lines of a text given by the user using through a Scanner(Obviously with an unknown number of words and lines), and finally printing these 2 numbers. All this using Java.

For now I've been trying for a few days to do the word count part(Since after doing this it would be very similar to code the lines part). I've tried a lot of things using arrays, split methods, etc. Now I have this code:

import java.util.Locale;
import java.util.Scanner;
import java.util.regex.Pattern;

public class WordCount {
     public static void main(String[] args) {

         int i=0;

         Scanner input = new Scanner(System.in).useLocale(Locale.US);

         while(input.hasNextLine()) {
            i++;
            input.next();
            }

         System.out.printf("%30s\n", "The text has " + i + " words");
     }
}

This count correctly the words in the text, however, since the while loop never ends, it never prints the total number of words and neither will continue with the following code when I write it.

Can someone help me solving this problem?

Thanks in advance!

Have a good day!

I would tweak your code to the following :

public static void main(String[] args) {
    Scanner input = new Scanner(System.in).useLocale(Locale.US);

    int lines = 0;
    int words = 0;

    String currLine = "?"; 
    while (currLine != null && currLine.trim().length() > 0) {
        currLine = input.nextLine();
        words = words + currLine.split("\\W+").length;
        lines++;
    }

    System.out.printf("%30s\n", "The text has " + (lines - 1) + " lines");
    System.out.printf("%30s\n", "The text has " + (words - 1) + " words");
    input.close();    
}
  • We need to use a variable to hold the input so I've used currLine to hold each line entered by the user.
  • Rename the variables to lines and word accordingly.
  • Use a regex to split each word and then calculate the length of the array and finally store it in words.

As soon as the user enters a blank line the program terminates.

Output :

asd asd asd asd asd asd asd asd

The text has 1 lines

The text has 8 words

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM