java - 为每一行文本文件创建对象

标签 java object constructor

我正在尝试做一些相对简单的事情;逐行读取文本文件,然后为每一行创建一个 '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/

相关文章:

java - 抑制 Java 中不推荐使用的导入警告

java转mysql jdbc连接问题

javascript - 如何在 Angular 中使用数组/对象循环遍历数组并为属性分配新值?

java - 在Java中通过txt文件创建对象到数组中

java - 用paint实例化一个类来制作一个正方形

c++ - 构造函数初始化和在构造函数中设置的私有(private)变量

java - Android 应用程序 Google 电子表格表单数据发布

java - 通过 java 驱动程序将数据从 MongoDB 转换为原生 MATLAB 格式

c# - base() 和 this() 构造函数最佳实践

java - 将值从构造函数传递到方法