Java Assignment Baby name popularity ranking The popularity
Java Assignment
(Baby name popularity ranking) The popularity ranking of baby names from year 2006 to 2015 can be downloaded from www.ssa.gov/oact/babynames and stored in files named babynamerank2006.txt, babynamerank2007.txt, …… babynamerank2015.txt. Each file contains 1000 lines. Each line contains a ranking, a boy’s name, number for the boy’s name, a girl name and number for the girl’s name. For example, the first two lines in the file babynameranking2010.txt are as follows:
1 Jacob 21,875 Isabella 22,731
2 Ethan 17,866 Sophia 20477
So the boy’s name Jacob and girl’s name Isabella are ranked #1 and the boy’s name Ethan and the girl’s name Sophia are ranked #2. 21875 boys are names Jacob and 22,731 girls are names Isabella in the year 2010.
Write a program that enables the user to select a year, gender, and enter a name to display the ranking of the name for the selected year and gender, as shown in the following figure. Prompt the user to enter another inquiry or exit the program. To achieve the best efficiency, create two arrays for boy’s names and girl’s names, respectively. Each array has 10 elements for 10 years. Each element is a map that stores a name and its ranking in a pair with the name as the key. Here is a sample run.
Solution
import java.io.File;
import java.util.Scanner;
public class BabyNames {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
do {
System.out.print(\"Enter the year:\");
int year = scanner.nextInt();
System.out.print(\"Enter the gender:\");
char gender = scanner.next().charAt(0);
System.out.print(\"Enter the name:\");
String name = scanner.next();
scanner = new Scanner(new File(\"babynamerank\" + year + \".txt\"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
String lineArr[] = line.split(\" \");
if (gender == \'M\') {
if (lineArr[1].equalsIgnoreCase(name)) {
System.out.println(\"Boy name \" + name
+ \" is ranked #\" + lineArr[0] + \" in year \"
+ year);
}
}
if (gender == \'F\') {
if (lineArr[3].equalsIgnoreCase(name)) {
System.out.println(\"Girl name \" + name
+ \" is ranked #\" + lineArr[0] + \" in year \"
+ year);
}
}
}
scanner = new Scanner(System.in);
System.out.print(\"Enter another enquary?\");
char ch = scanner.next().charAt(0);
if (ch == \'N\')
break;
} while (true);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
scanner.close();
}
}
}
OUTPUT:
Enter the year:2006
Enter the gender:M
Enter the name:Jacob
Boy name Jacob is ranked #1 in year 2006
Enter another enquary?Y
Enter the year:2006
Enter the gender:F
Enter the name:Sophia
Girl name Sophia is ranked #2 in year 2006
Enter another enquary?N
babynamerank2006.txt
1 Jacob 21,875 Isabella 22,731
2 Ethan 17,866 Sophia 20477

