Question: I need help with the code below. It is supposed to scan 10 txt files and give the top five boy and girl names for
I need help with the code below. It is supposed to scan 10 txt files and give the top five boy and girl names for each year from 2010 to 2001. It is in a file called: TopRankings. The files are called Babynamesranking(year).txt
I keep getting an InputMismatchException and I can't figure out what's wrong.
import java.util.ArrayList; import java.util.Scanner; public class TopRankingBabyNames { public static void main(String[] args) throws Exception { ArrayList boys = new ArrayList(); ArrayList girls = new ArrayList(); ArrayList line = new ArrayList(); //calling method printTableStructure(); //scan documents from 2010 to 2001 for(int year = 2010; year >= 2001; year--) { try { java.io.File file = new java.io.File("TopRankings/Babynamesranking" + year + ".txt"); Scanner input = new Scanner(file); for (int i = 0; i < 5 && input.hasNext(); i++) { readTxt(input, line); boys.add(line.get(1)); girls.add(line.get(3)); } } //exception catch (java.io.IOException ex) { System.out.println("I/O Errors: No Such File"); } //calling method printTableData(year, boys, girls); boys.clear(); girls.clear(); } } //print out the information in the table public static void printTableData(int year, ArrayList b, ArrayList g) { System.out.printf("%5d", year); for (int i = 0; i < 5; i++) { System.out.print(g.get(i)); } for (int i = 0; i < 5; i++) { System.out.print(b.get(i) + " "); printSpace((String) b.get(i)); } System.out.println(); } //print out the spaces public static void printSpace(String str) { int space = 10 - str.length(); for (int j = 0; j < space; j++) { System.out.print(" "); } } //print out the table titles and lines public static void printTableStructure() { System.out.println("-------------------------------------" + "----------------------" + "--------------------------------- " + "Year Rank 1 Rank 2 Rank 3 Rank 4 Rank 5" + " Rank 1 Rank 2 Rank 3 Rank 4 Rank 5 " + "-------------------------------" + "----------------------------------------------"); } //scan txt public static void readTxt(Scanner input, ArrayList list) { for (int i = 0; i < 5; i++) { int temp = input.nextInt(); list.add(temp + ""); } } public static String getURL(int year) { return "TopRankings/Babynamesranking" + year + ".txt"; } } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
