【发布时间】:2018-10-29 23:32:39
【问题描述】:
我是一名 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;
}
}
【问题讨论】:
-
您没有
break或continue语句,那么您认为while(file.hasNext())循环何时结束?所以一旦它结束,即file.hasNext()返回false,你认为当外循环条件调用file.next()时会发生什么?如果你认为NoSuchElementException失败,你是对的,所以外循环要么立即跳过,要么迭代一次然后死掉!如果您没有丢弃异常,您就会知道这一点。 不要丢弃异常。 -
您好,感谢您的快速回复!因此,如果我正确理解这一点,则 while(file.hasNext()) 返回一个布尔值。因此,一旦它在文件中搜索一次,它会在最后返回 false 并中断循环?假设我输入“Sam”作为输入,扫描仪不应该读取第一行,看到它不等于 sally,然后逐行读取,直到找到“Sam”?我想我很困惑为什么它不会检查起点(或者我如何检查每行中的第一个令牌)来查看我的输入是否等于那个令牌。非常感谢!
标签: java file-io text-processing