[英]Why won't my method read in every value from a file?
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);
}
I am trying to read in from a file a list of names and add them to an array list. 我正在尝试从文件中读取名称列表,并将其添加到数组列表中。 However there are duplicates of certain names and i am only suppoused to keep the unique ones (If if already exists don't add it again).
但是,某些名称存在重复项,我只是保留唯一的名称(如果已经存在,请勿再次添加)。 However, I figured out that it is only giving me every other name.
但是,我发现它只是给我其他名字。 Starting with 2, and giving me the following errors.
从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)
The reason of the exception in this line 该行出现异常的原因
if (BF.nextLine().equals(boysNames.get(i)))
you read a line and if equation isn't true
in else branch you call BF.nextLine()
again. 您读了一行,如果在else分支中方程不
true
,则再次调用BF.nextLine()
。 So sometimes you read line twice but you call hasNextLine()
only once . 因此,有时您读了两次行,但是只调用一次
hasNextLine()
。
Solution: read line only one time before if
statement. 解决方案:在
if
语句之前仅读取一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.