( Baby name popularity ranking ) The popularity ranking of baby names from years
ID: 3870228 • Letter: #
Question
(Baby name popularity ranking) The popularity ranking of baby names from years 2001 to 2010 is downloaded from www.ssa.gov/oact/babynames and stored in files named babynameranking2001.txt, babynameranking2002.txt, . . . , babynameranking2010.txt. Each file contains one thousand lines. Each line contains a ranking, a boy’s name, number for the boy’s name, a girl’s 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 20,477
So, the boy’s name Jacob and girl’s name Isabella are ranked #1 and the boy’s name Ethan and girl’s name Sophia are ranked #2. 21,875 boys are named Jacob and 22,731 girls are named Isabella. Write a program that prompts the user to enter the year, gender, and followed by a name, and displays the ranking of the name for the year. Here is a sample run:
*12.32 (Ranking summary) Write a program that uses the files described in Program- ming Exercise 12.31 and displays a ranking summary table for the first five girl’s and boy’s names as follows:
Year Rank 1 Rank 2 Rank 3 Rank 4 Rank 5 Rank 1 Rank 2 Rank 3 Rank 4 Rank 5
2010 Isabella Sophia Emma Olivia Ava Jacob Ethan Michael Jayden William
2009 Isabella Emma Olivia Sophia Ava Jacob Ethan Michael Alexander William
...
2001 Emily Madison Hannah Ashley Alexis Jacob Michael Matthew Joshua Christopher
I need help with 12.32 but I have to use txt files. Babynamesranking (year) .txt
Explanation / Answer
Here is the code for you:
import java.io.*;
import java.util.*;
public class BabyNamePopularityRanking {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.print("Enter year: ");
int year = sc.nextInt();
System.out.print("Enter gender: ");
char gender = sc.next().charAt(0);
System.out.print("Enter name: ");
String name = sc.next();
//File file = new File("babynamesranking" + year + ".txt");
sc.close();
sc = new Scanner(new File("babynameranking" + year + ".txt"));
if (sc == null) {
System.out.println("The database file doesn't exist");
return;
}
int rank = -1;
while (sc.hasNext()) {
String line = sc.nextLine();
String[] tokens = line.split(" ");
if ((gender == 'M' || gender == 'm') && tokens[1].contains(name))
rank = new Integer(tokens[0]);
else if ((gender == 'F' || gender == 'f') && tokens[3].contains(name)) //Which means if gender is female.
rank = new Integer(tokens[0]);
}
if (rank == -1) {
System.out.println("The name "+name+" is not ranked in year " + year);
} else {
System.out.println(name+" is ranked #"+rank+" in year "+ year);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.