public static int getBoys(ArrayList<String> boysNames, Scanner s) throws IOException {
// Getting boys file location
System.out.println("Please enter the file name containing the the boys names.");
String boyFileLocation = s.nextLine();
// Opening the file containing the names of boys
File boyFile = new File(boyFileLocation);
Scanner BF = new Scanner(boyFile);
int initialBoyCount = 0;
int i = 0;
boysNames.add(BF.nextLine());
while (BF.hasNextLine()) {
if (BF.nextLine().equals(boysNames.get(i))) {
} else {
boysNames.add(BF.nextLine());
initialBoyCount++;
i++;
System.out.println(boysNames.get(i));
}
}
return (initialBoyCount);
}
我正在尝试从文件中读入名称列表并将它们添加到数组列表中。然而,某些名称有重复,我只应该保留唯一的名称(如果已经存在,请勿再次添加)。然而,我发现它只是给了我所有其他的名字。从 2 开始,并给出以下错误。
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at namesList.namesList.getBoys(namesList.java:53)
at namesList.namesList.main(namesList.java:27)
最佳答案
该行异常的原因
if (BF.nextLine().equals(boysNames.get(i)))
您读了一行,如果 else 分支中的等式不true
,您将再次调用BF.nextLine()
。因此,有时您会读取该行两次,但只调用 hasNextLine()
一次。
解决方案:在 if
语句之前仅读取该行一次。
关于java - 为什么我的方法不能读取文件中的每个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35711173/