In: Computer Science
Write a program in Java that reads a file containing data about the changing popularity of various baby names over time and displays the data about a particular name. Each line of the file stores a name followed by integers representing the name’s popularity in each decade: 1900, 1910, 1920, and so on. The rankings range from 1 (most popular) to 1000 (least popular), or 0 for a name that was less popular than the 1000th name. A sample file called ‘population.txt’ has been given to you. Your program should prompt the user for a name and search the file for that name. If the name is found, the program should display the data about the name on the screen. If the name is not found, then display the message ‘Name not found in the file’
Your program should at-least have the following method:
checkName(): A method that takes the baby name as a parameter and returns true if the name exist and false otherwise.
Sample Output:
Name? Sam
Statistics on the name “Sam”
1900: 58
1910: 69
1920: 99
1930: 131
…
The file was not attached in question, So I created one and saved at location C:\population.txt
population.txt
I created an infinite loop and used the input "end" for stop
program
Program Result:
Code: Text Code Also Included in End
Code:
package javaapplication7;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.stream.Stream;
public class NamePopularity {
// Container For Store Names Data
private static HashMap<String, ArrayList>
namesData = new HashMap<>();
private static Scanner scanner = new
Scanner(System.in);
public static void main(String args[]) throws
IOException{
String fileName =
"population.txt";
String filePath = "C:\\" +
fileName;
// Reading File
Stream<String> lines =
Files.lines(Paths.get(filePath));
//Saving File Data
lines.forEach(s ->
saveData(s));
// Type end for exist from
loop
while(true){
System.out.println("Type Name For Search:");
String name
= scanner.next();
if(name.equals("end")){
System.out.println("Ending Program");
break;
}
if(checkName(name)){
printNameData(name);
}else{
System.out.println("Name Not Found in File");
}
}
}
// Storing Names Data In Hash Map using Key as
Person Name And Popularity As Array
private static void saveData(String data){
String[] splited =
data.split("\\s+");
ArrayList<String>
popularity = new ArrayList<>();
for(int i = 1; i <
splited.length; i++){
popularity.add(splited[i]);
}
namesData.put(splited[0], popularity);
}
// Checking Name
private static Boolean checkName(String
name){
if(namesData.containsKey(name)){
return true;
}else{
return false;
}
}
private static void printNameData(String
name){
ArrayList<String>
popularity = namesData.get(name);
System.out.println("Statistics of name \""+name +"\"");
int startYear =
1900;
for(String s:
popularity){
System.out.println(startYear + ": " + s);
startYear += 10;
}
}
}