Write a method that accepts a String object as an argument and returns the number of words it contains. For instance, if the argument is "Four score and seven years ago", the method should return the number 6. Demonstrate the method in a program that asks the user to input a string and then passes that string into the method, printing out whatever the method returns.

Respuesta :

Answer:

// Scanner class is imported so the program can receive input

import java.util.Scanner;

// The class Solution is defined

public class Solution {

   // main method that begin program execution

   public static void main(String args[]) {

     // scan object of Scanner is created

     Scanner scan = new Scanner(System.in);

     // A prompt is displayed to user to enter sentence

     System.out.println("Enter your sentence here: ");

     // THe user input is assigned to sentence

     String sentence = scan.nextLine();

     // The received input is pass to getStringNumber method

     getStringNumber(sentence);

   }

   

   // getStringNumber method is declared and receive sentence as args

   public static void getStringNumber(String sentence){

       // the received sentence is splitted by the space

       // the splitted sentence is assigned to an array

       String[] splitSentence = sentence.split(" ");

       // the length of the array is number of string in sentence

       System.out.println(splitSentence.length);

   }

Explanation:

The above code get the number of string in a sentence by splitting the sentence. The splitted sentence is assign to variable splitSentence. The length of splitSentence is output as number of strings.