2 回答
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
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);
}
添加回答
举报