Write a Java program that outputs a list of students from the given data file (h
ID: 3571546 • Letter: W
Question
Write a Java program that outputs a list of students from the given data file (home.txt). You have to input the name of the data file from keyboard. You have to use input.hasNext()with while loop when your program reads tokens from the file. We are assuming that you don’t know how many lines are in the data file. The file contains student name followed by their hometown. Your program should output each hometown, total number of students from each hometown, and each student’s name belonging in the hometown.
For example, if your data file contains the following data:
John Seattle
William Yakima
Susan Yakima
Jack Lapush
Jennifer Seattle
Kim Seattle
Your program should produce the following output (Bold is user input):
What is the file name? home.txt
Seattle students: 3
John
Jennifer
Kim
Yakima students: 2
William
Susan
Lapush students: 1
Jack
Explanation / Answer
Java program
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class SampleTest {
public static void main(String[] args) throws FileNotFoundException {
//Scanner used to take data from file
Scanner sc = new Scanner(new File("D://testdata//SampleData.txt"));
//Take a LinkedHashMap of type key as CityName and value as list of Student Names
LinkedHashMap<String, List<String>> hm =
new LinkedHashMap<String, List<String>>();
//hasNext() is a method in scanner class used to check whether there is next token or not
while(sc.hasNext())
{
//nextLine() is a method returns the current line
//split() is a method used to split a string of space delimiter
String arr[]= sc.nextLine().split(" ");
//List is used to collect the Student Names
List<String> li = new ArrayList<String>();
//containsKey() is a method used to check on a map whether it has key or not
//Here key is City Name
if(hm.containsKey(arr[1]))
{
//get() is method used to return the current value of specified key
li=hm.get(arr[1]);
//add() is a method in the list used to add Student Name into List
li.add(arr[0]);
}
else
{
li.add(arr[0]);
}
//put() is a method in the map used to put data on the map of key CityName and value
//as List of StudentNames
hm.put(arr[1], li);
}
//entrySet() is a method in map which return each Entry<Key,Value>
for(Map.Entry<String, List<String>> en:hm.entrySet())
{
//getKey() is a method used to getKey in Entry here key is CityName
//getValue() is a method used to getValue in Entry here value is List of Student Names
//size() is a method used to calculate no. of items in List
System.out.println(en.getKey()+" Students: "+en.getValue().size());
for(String name:en.getValue())
System.out.println(name);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.