将文件读入 Arraylist 但参数列表的长度不同

reading a file into an Arraylist but argument lists differ in length

我被文件 IO 的问题困住了。基本上,有一个名为 Student 的 class 和一个名为 readStudent 的方法,它将 return 一个 ArrayList 对象。

我被要求读取一个文件并将它们分成 3 个部分 space, 并且不允许使用扫描仪。

文件:

艾米摩尔 60 岁

克洛伊·斯科特 40 岁

我的问题是,(1) 由于 Student class 只有两个参数(String、Double),我如何将两个 String 和一个 Double 添加到 Student 中? (2) Student class提供的没有toString()方法,如何打印出来?

如果有人能帮助我,我将不胜感激。

Student 的构造函数如下:

 public Student(String sstudent, double mmark) 

读学生:

 public static ArrayList<Student> readStudent(String fName){

到目前为止我做了什么:

 ArrayList<Student> list=new ArrayList<Student>();
 try{

    BufferedReader br=new BufferedReader(new FileReader(fName));

     String line;

     while((line=br.readLine())!=null){


        String[] splitLine=line.split(" ");
        String first=splitLine[0];
        String second=splitLine[1];
        Double third=Double.parseDouble(splitLine[3]);

       Student stu=
            new Student(first,second));


        list.add(stu);


    }

  ...... 

  return list;

}

针对你的问题(1)

Student s = new Student(first + " " + second, third);
//by the way for third,it is not splitLine[3],it is splitLine[2]

针对你的问题(2)

ArrayList<Student> studentList = readStudent("YourFileName");
for(Student s : studentList)
    System.out.println(s.name + " " + s.grade);//don't know what are the variable names of Student class instances

您在代码中有不同的选择: //问题1(见上面第一条评论):
如果您出于任何原因不需要第一、第二和第三,请选择选项 1(它很有效)。

public static ArrayList<Student> readStudent(String fName) throws FileNotFoundException, IOException{

        ArrayList<Student> list=new ArrayList<Student>();
        //try{

        BufferedReader br=new BufferedReader(new FileReader(fName));

        String line;

        while((line=br.readLine())!=null){

            //option1
            String[] splitLine=line.split(" ");
            Student stu = new Student(splitLine[0] + " " + splitLine[1], splitLine[2]);

            //option2
//            String first=splitLine[0];
//            String second=splitLine[1];
//            double third=Double.parseDouble(splitLine[3]);            
//            Student stu = new Student(first + " " + second, third); 


            list.add(stu);


        }

        //......

        return list;
    }

//问题2:
在 java 中,getter 和 setter 用于访问 class 的属性(这是首选样式)。检查class学生中是否有一些然后使用它。
在选项 2 中,您可以访问学生对象的方向全局变量。

printStudents(readStudent("your file name"));     //print a list of student objects 

void printStudents(List<Student> students){
    for(Student stu: students)
        //option 1: using getter
        System.out.println(stu.getSStudent()+"  "+stu.getMark());

        //option 2: accessing attributes 
        //System.out.println(stu.sstudent+"  "+stu.mark);
}