Java: Chapter 4 Number 11: 11. Write a method called longestName that accepts a
ID: 3676753 • Letter: J
Question
Java: Chapter 4 Number 11:
11. Write a method called longestName that accepts a Scanner for the console and an integer n as parameters and IL Write a method calld longestHame tht acepts a scanner for the console and an ineger as araners and prompts for n names, then prints the longest name (the name that contains the most characters) in the format shown below, which might result from a call of longestName (console, 4): name #1? Roy name #2? DANE name #3? sTeFaNE name #4? Mariana Stefanie's name is longestExplanation / Answer
Answer:
NameLength.java
import java.util.*;
import java.io.*;
public class NameLength {
public static void main(String[] args) {
Scanner read=new Scanner(System.in);
System.out.println("Enter number of names to be accepted:");
int NUM_NAMES = read.nextInt();
Scanner console=new Scanner(System.in);
//System.out.println("Please Enter The Names: ");
longestName(console,NUM_NAMES);
}
public static void longestName(Scanner console,int NUM_NAMES)
{
String longest_string = "";
for(int i=0; i<NUM_NAMES; i++){
System.out.print("name # "+(i+1)+": ");
String str=console.nextLine();
if( str.length() > longest_string.length() )
{
longest_string = str;
}
}
System.out.println(longest_string+" 's name is longest");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.