2015-05-07 85 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检查以确保您有足够的数组元素来解析出所有字段。或者,如果您知道该文件是一致的,只需将您的解析与您的文件相匹配即可。