为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

心有法竹 2022-09-22 10:23:48
我被困在一个文件IO的问题上。基本上,有一个名为“学生”的类,还有一个名为“读取学生”的方法,它将返回一个 ArrayList 对象。我被要求读取一个文件,并通过单个空格将它们分成3个部分,并且不允许使用扫描仪。文件:艾米·摩尔 60克洛伊·斯科特 40我的问题是,(1)由于学生类只有两个参数(字符串,双精度),我如何将两个字符串和一个双精度添加到学生中?(2)学生班级提供的没有toString()方法,我该如何打印出来?如果有人能帮助我,我将不胜感激。学生的构造函数是这样的: 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;}
查看完整描述

2 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

对于您的问题 (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


查看完整回答
反对 回复 2022-09-22
?
桃花长相依

TA贡献1860条经验 获得超8个赞

您在代码中有不同的选择://问题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 中,获取器和设置器用于访问类的属性(它是首选样式)。检查是否有一些在课堂上的学生,然后使用它。

在选项 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);

}


查看完整回答
反对 回复 2022-09-22
  • 2 回答
  • 0 关注
  • 52 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信