你朝着正确的方向前进。记住要始终将代码组织成逻辑单元,这有助于概念化过程,以及程序的维护。
public List> parseRatingsFile(String fileName) throws IOException {
List> ratings2DArray = new ArrayList>(16);
final BufferedReader in = new BufferedReader(new FileReader(fileName));
String ratingsLine = null;
while ((ratingsLine = in.readLine()) != null) {
ratings2DArray.add(parseRatingsLine(ratingsLine));
}
in.close();
return ratings2DArray;
}
public List parseRatingsLine(String ratingsLine) IOException {
List ratings = new ArrayList(8);
if(ratingsLine == null) return ratings;
String[] ratingsStrArr = ratingsLine.split(" "); // Tokenize on 'space' character
for(final String ratingStr: ratingsStrArr) {
// Here you would parse the ratingStr as an Integer, and
// add it to your list
}
return ratings;
}您应该处理在解析单个整数时可能出现的NumberFormatExceptions。您会注意到我删除了counter变量,它会使您的程序更复杂,并且可能成为错误的来源。祝其余的功课好运。