Write a program that reads in text from standard input (hint: use Scanner) and prints out the number of words in the text. For the purpose of this exercise, a word is a sequence of non-whitespace characters that is surrounded by whitespace.

Respuesta :

Answer:

The solution code is written in Java

  1.        Scanner input = new Scanner(System.in);
  2.        System.out.print("Enter a text: ");
  3.        String inputStr = input.nextLine();
  4.        String wordList[] = inputStr.split(" ");
  5.        System.out.println("The number of word in the input text: " + wordList.length);

Explanation:

Firstly, create a Scanner object to read the user input text using nextLine method (Line 1-3).

Next, we can use the string split method and use single space " " as the separator to convert the input text to an array of individual word (Line 5).

We can simply use println to display the number of words in the array by using the length property of the array (Line 7). The word count is equal to the array length.