Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Financial management theory and practice

Authors: Eugene F. Brigham and Michael C. Ehrhardt

12th Edition

978-0030243998, 30243998, 324422695, 978-0324422696

Students also viewed these Programming questions