Java(构造函数问题)
试图弄清楚如何将CSV文件读入构造函数。主题是哈利·波特,我正在阅读4个文件(格兰芬多,赫奇帕奇,拉文克劳,斯莱特林)。将其读入我的 House.java ,但是 School.java 和 Student.java 也具有构造器/获取器和设置器。在下面提供。例如,在学校内的a中有一个房屋,而在其中有学生。在提供的4个CSV文件中,每个文件都是一个“房屋” 的名称,您可以在其中以“学生” 的名称读取文件(名字,姓氏,年)。
这3个Java文件位于application.model中,以支持使用MVC格式的JavaFX中的应用程序。为了评分,它是专门为此定制的。
House.java
public class House {
private String name;
private String color;
private String professor;
public ArrayList<Student> Students;
public House(String name, String color, String professor, ArrayList stdList) {
this.name = name;
this.color = color;
this.professor = professor;
this.Students = stdList;
}
public ArrayList<Student> sortStudents(ArrayList<Student> allStudents) {
if (allStudents != null) {
Collections.sort(allStudents, new SortTool());
}
return allStudents;
}
public void dataLoader() {
String fileName = "Gryffindor.csv";
String content = null;
/*
* Shows working path System.out.println(newFile(".").getAbsoluteFile());
*/
try {
Scanner inputStream = new Scanner(new File(fileName));
// Delimits by commas and (enter or \n)
inputStream.useDelimiter("[,\n]");
// Iteration rather than iterable
while (inputStream.hasNext()) {
content = inputStream.nextLine();
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
School.java
public class School {
private String name;
private int enrollment;
private House houses[];
/*
* School Constructor
*
* @param pass in name to set name
*/
public School(String name) {
this.name = name;
houses = new House[4];
enrollment = 0;
}
}
Student.java
public class Student {
private String firstName;
private String lastName;
private int year;
public Student(String firstName, String lastName, int year) {
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
}
}
SortTool.java 公共类SortTool实现Comparator {
@Override
public int compare(Student a, Student b) {
int c = a.getYear() - b.getYear();
if (c == 0)
c = a.getLastName().compareTo(b.getLastName());
if (c == 0)
c = a.getFirstName().compareTo(b.getFirstName());
return c;
}
}
自从我写了整个程序以来,一直试图使其与众不同,并且不希望其被窃。 House.java-如何将这个CSV文件读入构造函数。逗号已取消,需要阅读且无需手动输入。
Gryffindor.csv的示例
Colin Creevy,1,Hermione Granger,2,Harry Potter 2,
答案 0 :(得分:0)
那么您可以读取House类的构造函数文件。只需添加一个私有方法即可填充Student arrayList。 您必须打开文件,提供每个房屋文件所在的路径,并在其后附加“ /”+this.name+”.csv”,然后对读取的文件的每一行进行解析并添加新的数组列表中的学生。 方法示例:
private void populateHouseFromFile(){
String line;
br = new BufferedReader(new FileReader(PATH_TO_HOUSES+"/"+this.name+".csv"));
while ((line = br.readLine()) != null) {
String[] split = line.split(",",3); //Retrieve each part of the student information , assuming each field is separated with a "," and each line is new entry.
this.Students.add(new Student(split[0],split[1],Integer.decoded(split[2])));
}
}
您应检查int的学生构造函数是否传递的参数不愚蠢(负数,如果构造不好的.csv,则为负,等等)。