Question: zyDE 6.7.1: Use a single Scanner to read input. The following program counts the total number of letters in a person's first and last names.

zyDE 6.7.1: Use a single Scanner to read input.

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.

  1. Run the program. Note that the program does not count letters in the last name. The first call toscnr.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.
  2. Change the program by passing a Scanner to the getAndCountNameLetters() method.
  3. Run the program again. Note that the count now includes the last name.

import java.util.Scanner;

public class NameLettersCounter {

// FIXME: Specify a Scanner as a method parameter

public static int getAndCountNameLetters() {

// FIXME: Use the Scanner parameter instead of creating one every time

Scanner scnr = new Scanner(System.in);

String name = "";

if (scnr.hasNext()) {

name = scnr.next();

}

return name.length();

}

public static void main(String[] args) {

int firstNameLetterCount;

int lastNameLetterCount;

// FIXME: Create Scanner here

System.out.println("Enter a person's first and last names:");

// The first method call will read both first and last names

// FIXME: Pass the Scanner as an argument to both method calls

firstNameLetterCount = getAndCountNameLetters();

lastNameLetterCount = getAndCountNameLetters();

System.out.println("The first name has " + firstNameLetterCount + " letters.");

System.out.println("The last name has " + lastNameLetterCount + " letters.");

}

}

I have tried quite a few different methods trying to get this to work. However, whenever I add another scanner I either get an error saying my word does not exist, or it overrides the first scanner and I get 0 for both of my answers.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!