我正在尝试做一些相对简单的事情;逐行读取文本文件,然后为每一行创建一个 'Course'
对象。然后我想将每个对象添加到一个新的 'CourseList'
对象,该对象将在实例方法中返回。
这是我目前所拥有的:(我只是在方法中包含了我的尝试部分)
try {
FileReader reader = new FileReader(inputName);
BufferedReader inFile = new BufferedReader(reader);
String nextLine = inFile.readLine();
Course newObject = new Course();
CourseListQ2 newList = new CourseListQ2();//entire object to be returned
while(nextLine!=null){
newList.addCourse(newObject);
}
return newList;
inFile.close();
}
Course newObject = new Course();
行出现错误:
错误:类 Course 中的构造函数 Course 不能应用于给定类型; 必需:java.lang.String,java.lang.String,int
所以我不认为我理解如何为每一行创建一个 Course
对象。甚至那真正意味着什么。有什么建议吗?
最佳答案
您的代码中几乎没有更正:
Course newObject = new Course();//constructor requires 3 params of String, String and int, what you get as compile time error.
CourseListQ2 newList = new CourseListQ2();
while(nextLine!=null){//you are not reading the next line, so it will be a infinite loop after reading the first line of file
newList.addCourse(newObject);//adding same course object instead you need different courses from each line
}
return newList;//must be after the below line
inFile.close();//in future compiler is gona give error for writing below return keyword
已编辑 你可以试试这个代码:
CourseListQ2 newList = new CourseListQ2();
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader(inputName));
String nextLine;
String param1;
String param1;
int param3;
while(null != (nextLine = inFile.readLine())){//read line by line
param1 = your code here to play with nextLine
param2 = your code here to play with nextLine
param3 = your code here to play with nextLine
newList.addCourse(new Course(param1, param2, param3));
}
} catch(IOException ex) {
ex.printStackTrace(System.err);//print exception on console
} finally {//its optional but recommended
if(null != inFile) {
try {
inFile.close();//may cause trouble
} catch(IOException ex) {
ex.printStackTrace(System.err);//print exception on console
}
}
return newList;
}
关于java - 为每一行文本文件创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28640587/