Я студент CS210, и у меня возникают проблемы с проверкой текстового файла на наличие нескольких имен для извлечения данных из него.Мне даны следующие данные для хранения в текстовом файле.Это имя, за которым следуют 11 целых чисел для чтения данных:
-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
Следующий код хорошо работает для первого имени в группе (Салли) и работает правильно.Но программа ничего не возвращает в консоль для Сэма, Саманты или Самира.Я не уверен, почему он будет работать правильно для одного, но не работает для других.
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;
}
}