Respuesta :
Answer:
// import the Scanner class to allow for user input
import java.util.Scanner;
// define a class for the program
public class NumOfWordsAndChars {
// the main method
public static void main(String[] args) {
// create an object of the Scanner class, call it input
Scanner input = new Scanner(System.in);
//1. Prompt the user to enter their name
System.out.println("Please enter your name");
//using the input object, receive and store the entered
//name in a string variable called name.
String name = input.nextLine();
// declare and initialize to zero, a variable noOfWords
// that will hold the number of words in the name.
int noOfWords = 0;
// 2. Get the number of words.
// Check to see if the user actually entered a name.
// If they did enter a name, use the split() function to break
// the entered name into its constituent words and store
// these words in an array variable called words.
// From the words array, the number of words can be found
// by simply getting the length of the array using words.length
// Store the number of words in the variable noOfWords
if (name != null && !name.isEmpty()){
String words [] = name.split("\\s+");
noOfWords = words.length;
}
// 3. Get the number of characters.
// the number of characters in a string is found using the function lenght()
// store the number of characters in an integer variable, noOfChars
int noOfChars = name.length();
// 4. Display the number of words and characters
System.out.println("No of words: " + noOfWords);
System.out.println("No of characters: " + noOfChars);
} // End of main method
} // End of the class declaration
Explanation:
The above code has been written in Java.
The code contains comments explaining every part of the code. Please carefully go through the comments in the code.
The source code has also been attached to this reponse. Please download the file and you may run it on your Java enabled local machine.
Note that the split() function in the code receives an argument which is a regular expression representing one or more whitespace characters i.e \\s+.
This means that the string (name) should be split into its constituent words since a word is typically a non-space character in a string.
Hope this helps!