【问题标题】:How to read in from a file and create new objects with input from the read file如何从文件中读取并使用读取文件中的输入创建新对象
【发布时间】:2016-12-13 00:48:20
【问题描述】:

读入学生档案。为每个学生 ID 创建一个学生对象。将该对象名称设置为文件中学生 ID 后面的名称。以学生 ID 作为键,将 Student 对象添加到地图中。 读入课程文件。对于每个学生 ID,从地图中查找 Student 对象。阅读文件中的学分行。阅读文件中的成绩行。使用学分和成绩创建课程对象。将该 Course 对象添加到 Student 对象的课程集合中。

这是我从文件中读取信息的代码:

    FileReader freader = new FileReader(nameFile);
    BufferedReader Breader = new BufferedReader(freader);
    boolean end = Breader.ready();

        do {
            next = Breader.readLine();
            sNumber = Integer.parseInt(next);
            formatSNumber = String.format("%03d", sNumber);
            //Assignment the formatted number to my HashMap
            sName = Breader.readLine();
            //Assignment the name to my HashMap
            end = Breader.ready();
        } while(end);

我完全不知道该怎么做。

我知道如何创建一个学生对象:

Student student1 = new Student();

但是,我需要每个名字“student1”根据读入的信息而有所不同。

例如,如果我读到“001”和“Julie Jones”,我希望我的学生对象是

Student student1 = new Student();

然后是下一个

Student student2 = new Student();

对于学生 studenti = new Student();,其中 i = 从文件中读取的学生 ID 数。

【问题讨论】:

  • 什么是Breader?这个类不是标准 JDK 的一部分。
  • 它是 BufferedReader 的一个实例。抱歉,为了清楚起见,我添加了一些代码。
  • 创建一个学生对象如果这超出了你的能力范围,那么我建议你接受一对一的辅导
  • 必须有数百个关于如何在 SO 上找到的文本文件中读取的示例
  • 您不需要为您的Student 指定不同的变量名称因为 每次循环迭代它都会重新声明 Student 对象并且代码重新初始化将存储在学生对象中的值。这些对象可以在循环内添加到ArrayList

标签: java file hashmap


【解决方案1】:

哟,我认为这个问题有点误导。 “对象名称”是指学生姓名,而不是对象引用变量的名称。我正在阅读的是,您将需要创建一个学生对象,并将其名称作为参数传入。

我认为应该是这样的(伪代码):

//create a map//
for each line in file {
    int id=//GET THE ID//
    String name=//GET THE STUDENTS NAME//
    Student student=new Student(name);
    map.add(student, id);
}

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2018-08-08
    • 2013-10-12
    • 2011-07-18
    • 1970-01-01
    相关资源
    最近更新 更多