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.
- 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.
- Change the program by passing a Scanner to the getAndCountNameLetters() method.
- 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
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started