簡體   English   中英

為什么我的方法不能從文件中讀取每個值?

[英]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);
}

我正在嘗試從文件中讀取名稱列表,並將其添加到數組列表中。 但是,某些名稱存在重復項,我只是保留唯一的名稱(如果已經存在,請勿再次添加)。 但是,我發現它只是給我其他名字。 從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語句之前僅讀取一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM