2015-05-07 88 views
-1

,因此此代碼旨在打開具有正確名稱的文本文件,然後用於分隔程序在每個逗號後讀取的每行,文本文件的一個示例是:從文本文件中讀取數據並將行分開讀取

Germany,5,3,6,2,3 
Argentina,3,5,2,1,1 
+0

在這裏看到字符串'「德國,5,3,6,2,3」'總逗號分隔值是6.所以它顯而易見,如果你嘗試使用'newStrings [6]',它會拋出'ArrayIndexOutOfBoundsException '。 –

+0

您正試圖讀取7個元素(從索引0到6),但您的示例只有6個元素。所以它會在這一行失敗:> NewTeam.setTotalPoints(Integer.valueOf(newStrings [6])); – User404

+0

如果我刪除「NewTeam.setTotalPoints(Integer.valueOf(newStrings [6]))」然後我得到「ArrayIndexOutOfBoundsException:1」 - 爲什麼? – fmorgan91

回答

1

之前的循環可能收集隊:

List<Team> teams = new ArrayList<>(); 

在循環內部檢查,你必須確實7場(想到空線,數據錯誤)

if (newStrings.length != 7) { 
    System.out.println("Error in line: " + currentLine); 
    continue; // Still handle rest 
} 

此外,當你做在整個線路上分裂,忘記掃描儀lineScanner,這是多餘的。

 while ((currentLine = bufferedReader().readLine()) != null) { 

或多個可讀:

 for (;;) { 
      String currentLine = bufferedReader().readLine(); 
      if (currentLine == null) { 
       break; 
      } 

在循環:

  teams.add(newTeam): 

是這樣的:

List<Team> readTeams() throws IOException { 
    OUDialog.alert("Select input file for " + this.getPoolName()); 
    String fileName = OUFileChooser.getFilename(); 
    Path aFile = Paths.get(fileName); 
    try (BufferedReader bufferedFileReader = Files.newBufferedReader(aFile)) { 
     String currentLine = bufferedFileReader.readLine(); 
     if (currentLine != null && currentLine.equals(this.getPoolName())) { 
      List<Team> teams = new ArrayList<>(); 

      while ((currentLine = bufferedReader.readLine()) != null) { 
       String[] newStrings = currentLine.split(","); 
       if (teams.length == 0) { 
        continue; // Allow empty lines 
       } 
       if (teams.length != 7) { 
        throw new IOException("Wrong line:" + currentLine); 
       } 
       Team newTeam = new Team(newStrings[0]); 
       newTeam.setWon(Integer.valueOf(newStrings[1])); 
       newTeam.setDrawn(Integer.valueOf(newStrings[2])); 
       newTeam.setLost(Integer.valueOf(newStrings[3])); 
       newTeam.setFourOrMoreTries(Integer.valueOf(newStrings[4])); 
       newTeam.setSevenPointsOrLess(Integer.valueOf(newStrings[5])); 
       newTeam.setTotalPoints(Integer.valueOf(newStrings[6])); 
       teams.add(newTeam); 
      } 
      return teams; 
     } else { 
      throw new IOException("Wrong file selected"); 
     } 
    } // Closes always. 
} 

這將報告錯誤作爲例外。

+0

如果我刪除了lineScanner循環不會繼續,currentLine將設置爲bufferedReader並檢查它是否是正確的文件,如果它是然後lineScanner接管並讀取行。有沒有更好的方法來做到這一點? – fmorgan91

+0

好的,我已經編碼出來了。 –

2

ArrayIndexOutOfBoundsException表示您試圖訪問數組中不存在的索引。看看你的代碼和你的樣本輸入,你試圖訪問數組中的7個元素(索引0-6),但是輸入只有6個輸入,這意味着只要它試圖調用NewTeam.setTotalPoints(Integer.valueOf(newStrings[6]));就會拋出異常。

簡單的解決方法是在解析數組之前驗證您的數組:將newStrings.length檢查以確保您有足夠的數組元素來解析出所有字段。或者,如果您知道該文件是一致的,只需將您的解析與您的文件相匹配即可。