为什么我的程序不会从文本文件中重新标记所有名称?

时间:2018-05-19 21:39:35

标签: java file-io text-processing

我是一名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

以下代码适用于组中的第一个名称(Sally)并正确运行。但是对于Sam,Samantha或Samir而言,该程序并没有向控制台返回任何内容。我不确定为什么它会为一个人正常工作,但不能为其他人工作。

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;
}

}

1 个答案:

答案 0 :(得分:1)

问题是nameCheck没有更新为文件中的下一个标记。您需要在while循环中移动nameCheck,以便更改每个循环。此外,您不需要while(!name.equals(file.next()))),因为如果名称匹配是file.next,则循环将终止而不是计算整数的总和。代码适用于第一个,因为它是列表中的第一个,因此nameCheck不需要更新,而file.next()将是下一个而不是第一个。您的代码应如下所示:

try{
    while(file.hasNext()){
        String nameCheck = file.next();
            if (nameCheck.equals(name)){
                //code for calculating sum
             }
    }
 }