如何创建一个for循环,该循环生成从文本文件读取值的不同对象? 我的文本文件:
1, Title1, 1
AM, AP
9, 8, 7
2, Title2, 2
AM, PS, TC
10, 8
3, Title3, 3
AM, PP
1, 2, 4
4, Title4, 2
JD
6
答案 0 :(得分:0)
引起问题的是在while循环中使用的readLine()方法,该方法将指针向前移动了一行(到包含1, Title1, 1
的第一行)。
第二次在for循环本身的第一行中调用readLine(),现在将光标移至第二行(即AM, AP
)
希望您知道错误从何而来。
我可以建议您移动循环的第一行吗?
for (int i=0; i<N; i++){
line= br.readLine(); //this line
String[] tokens = line.split(",");
到最后
collection.addPaper(objectX); //adding object into the collection
line= br.readLine(); //move it here
}
System.out.println("Worked");
希望您能理解我的建议以及原因!
我记得,FileReader跳过空行。 (仅包含\ n)
或者,删除while循环本身也可以解决。
答案 1 :(得分:0)
您应该在代码中解决以下问题:
for
循环。List<String> author = new ArrayList<String>();
代替ArrayList<String> author = new ArrayList<String>();
null
。 String
值,然后将其解析为int
。paperTitle = tokens[2]; //Storing second value
应该为paperTitle = tokens[1];
以下是结合了上述所有要点的代码:
try {
File file = new File("C:\\Users\\hi123\\Desktop\\input1.txt");
br = new BufferedReader(new FileReader(file));
String line;
int paperId;
String paperTitle;
int quartile;
List<String> author = new ArrayList<String>();
List<Integer> scoreReview = new ArrayList<Integer>();
while ((line = br.readLine()) != null) {
String[] tokens = line.split(",");
paperId = Integer.parseInt(tokens[0].trim()); //First value in the array
paperTitle = tokens[1].trim(); //Second value in the array
quartile = Integer.parseInt(tokens[2].trim()); //Third value in the array
line = br.readLine(); //Read next line
String[] tokensAuthor;
if ((line = br.readLine()) != null) {
tokensAuthor = line.split(",");
}
if (tokensAuthor != null) {
for (int j = 0; j < tokensAuthor.length; j++) {
author.add(tokensAuthor[j].trim());
}
}
line = br.readLine(); //Read next line
String[] tokensInt;
if ((line = br.readLine()) != null) {
tokensInt = line.split(",");
}
if (tokensInt != null) {
for (int j = 0; j < tokensInt.length; j++) {
scoreReview.add(Integer.parseInt(tokensInt[j].trim()));
}
}
PaperCollection collection = new PaperCollection();
Paper objectX = new Paper(paperId, paperTitle, quartile, author, scoreReview);
collection.addPaper(objectX); // adding object into the collection
}
System.out.println("Worked");
} catch (Exception e) {
e.printStackTrace();
}