2016-02-29 55 views
0
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) 

回答

1

例外的在這條線

if (BF.nextLine().equals(boysNames.get(i))) 

你讀一條線,如果公式是在else分支沒有true你再打電話BF.nextLine()原因。所以有時你讀兩遍,但你只需撥打hasNextLine()一次。

解決方案:僅在if聲明前一行讀取一行。

+0

我明白你的意思了。那麼有什麼方法可以在不移動標記的情況下兩次引用文件中的內容? –

+1

@ M.Pestonit解決方案:你只能調用'hasNextLine()'和'BF.nextLine()'一次。我剛剛改變了我的答案,解決方案應該如何。 –

+1

@Andriy嘗試將'String currentLine = BF.nextLine()'作爲while循環的第一行。然後引用'currentLine'而不是'BF.nextLine()'。 – GreenGiant

相關問題