I'm a CS210 student and I am having trouble checking a text file for multiple names to pull data from it. I'm given the following data to store in a text file. It is a name, followed by 11 integers to read data from:
-Sally 0 0 0 0 0 0 0 0 0 0 886
-Sam 58 69 99 131 168 236 278 380 467 408 466
-Samantha 0 0 0 0 0 0 272 107 26 5 7
-Samir 0 0 0 0 0 0 0 0 920 0 798
The following code works well for the first name in the group (Sally) and runs correctly. But for the program doesn't return anything to the console for Sam, Samantha or Samir. I'm not sure why it will work correctly for one, but not work for the others.
import java.util.*;
import java.io.*;
public class TestSpace1 {
public static void main(String[] args) throws FileNotFoundException{
Scanner fileInput = new Scanner(new File("names.txt"));
String nameUsed = nameSearch();
dataScan(fileInput, nameUsed);
}
public static void dataScan(Scanner file, String name) {
String nameCheck = file.next();
try{
// While there are still tokens to be read in the file
while(!name.equals(file.next())) {
while(file.hasNext()) {
// If the name is equal to the next String token in the file
if (nameCheck.equals(name)) {
// Initialize variable to contain start year
int year = 1910;
// Run through for loop to add up the integers and display them in value pairs for the year
for (int i = 0; i < 11; i++) {
int ranking = file.nextInt();
System.out.println(year + ": " + ranking);
year += 10;
}
// If the file doesn't read the name, loop to the end of the line, start at top of loop
} else {
file.nextLine();
}
}
}
// If there is a line out of bounds, catch exception
} catch (Exception e) {
System.out.println("All lines have been read");
}
}
public static String nameSearch() {
Scanner input = new Scanner(System.in);
System.out.println("This program allows you to search through the");
System.out.println("data from the Social Security Administration");
System.out.println("to see how popular a particular name has been");
System.out.println("since 1900.");
System.out.print("What name would you like to search? ");
String name = input.nextLine();
return name;
}
}