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)
答案 0 :(得分:1)
此行中出现异常的原因
if (BF.nextLine().equals(boysNames.get(i)))
你读了一行,如果在else分支中没有true
等式,你再次调用BF.nextLine()
。所以,有时你会读两次行,但只打一次hasNextLine()
。
解决方案:仅在if
语句之前读取一行。