所以这段代码打算用正确的名字打开一个文本文件,然后它意味着在每个逗号之后分割程序读取的每一行,
文本文件中的一个例子是:
Germany,5,3,6,2,3
Argentina,3,5,2,1,1
答案 0 :(得分:2)
CREATE TYPE LIST_OF_PARAMS AS TABLE (id int, NAME VARCHAR)
go
CREATE PROCEDURE Myproc @Mytable LIST_OF_PARAMS READONLY,
@id INT
AS
BEGIN
表示您正在尝试访问数组中不存在的索引。查看您的代码和示例输入,您试图访问数组的7个元素(索引0-6),但输入只有6个输入,这意味着只要它尝试调用ArrayIndexOutOfBoundsException
它就会抛出一个异常。
简单的解决方法是在解析之前验证您的数组:进行NewTeam.setTotalPoints(Integer.valueOf(newStrings[6]));
检查以确保您有足够的数组元素来解析所有字段。或者,如果您知道文件是一致的,只需将解析与文件匹配即可。
答案 1 :(得分: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.
}
这会将错误报告为异常。