You must: Comment and Format and Must make sure about indenting. If you don\'t f
ID: 3607018 • Letter: Y
Question
You must: Comment and Format and Must make sure about indenting. If you don't follow these steps, it will be flagged for review.
Exercise 4. Write a program that keeps track of students in a class. The program will prompt the teacher to enter the total number of students. Then the teacher will input the last names of all the students (multiples of the same last name are possible). Next, the program will ask the teacher to enter a name. The program will print out the indices of all matching last names in the array (or a message that the name is not in the array). The program will then ask the teacher to enter a letter, after which the program will print out all the unique names in the array that start with that letter. Finally, the program will print out the name(s) with the longest number of letters. See below for sample output: Please enter the total number of students: 7 Enter the last name: Smith Enter the last name: Jian Enter the last name: Theriault Enter the last name: Jones Enter the last name: Dillon Enter the last name: Branson Enter the last name: Jannis Enter a name to search for: Branson Branson is at index 5 Enter a letter to search on: J The last names that start with J: Jian Jones Jannis The longest name is Theriault with 9 letters Provide: Printout of properly formatted source code Example output/test cases (2 test cases different than above) -Explanation / Answer
Final -
import java.io.*;
import java.util.*;
class A
{
public static void main(String args[])
{
int i =0 , ind=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter number of students : ");
int n=sc.nextInt();
String names[]=new String[n];
int a[]=new int[n];//to store the length of the strings or names
for(i=0;i<n;i++)
{
Scanner sc1=new Scanner(System.in);
System.out.print(" Enter last name : ");
names[i]=sc1.nextLine();
}
System.out.println(" Enter name to search :");
Scanner sc2=new Scanner(System.in);
String name=sc2.nextLine();
for(i=0;i<n;i++)
{
if(name.equals(names[i]))
{
System.out.println(" "+name+ " is at index "+(i));
}
}
System.out.println(" Enter character to search name on : ");
char ch=sc.next().charAt(0);
System.out.println(" The last name starting with "+ch+" are");
a[0]=names[0].length();//first name's length
int max=a[0];
for(i=0;i<n;i++)
{
a[i]=names[i].length();
if(ch==(names[i].charAt(0)))
//to calculate the string length
{
System.out.print(names[i]+" ");
}
if(a[i]>max)
{
ind=i;
max=a[i];
}
}
System.out.println();
System.out.println("Longest last name is "+names[ind]+" with " +max +" letters ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.