The following program counts the total number of letters in a person's first and last names. The getAndCountNameLetters() method creates a Scanner, reads a name from the user input, and returns the number of letters. Run the program. Note that the program does not count letters in the last name. The first call to scnr.next() returns the first name, but also reads the last name to make future reads faster. The second call to getAndCountNameLetters() creates a different Scanner, which has nothing left to read. Change the program by passing a Scanner to the getAndCountNameLetters() method. Run the program again. Note that the count now includes the last name.

Respuesta :

Answer:

import java.util.Scanner;

public class NameCount

{

public static void main(String[] args) {

    int firstNameCount = 0;

    int lastNameCount = 0;

    Scanner scnr = new Scanner(System.in);

 System.out.print("Enter the person's first and last name: ");

 

 firstNameCount = getAndCountNameLetters(scnr);

 lastNameCount = getAndCountNameLetters(scnr);

 

 System.out.print("The first name has " + firstNameCount + " letters");

 System.out.print("The last name has " + lastNameCount + " letters");

}

public static int getAndCountNameLetters(Scanner scnr) {

    String name = "";

   

    if(scnr.hasNext())

        name = scnr.next();

       

   return name.length();

}

}

Explanation:

Create a method called getAndCountNameLetters that takes one parameter, a Scanner object

Inside the method:

Initialize a variable called name

Read the input and assign it to the name variable

Return the name

Inside the main:

Initialize count variables for first and last name

Get the name from the user

Set the first and last name's count by calling the method getAndCountNameLetters

Print the counts