What is the return type of list<student>?

时间:2015-06-26 09:31:34

标签: java return

I want to create a method to populate the data of student with the method signature as public List<student> populateData(String filename).

I am new in Java. Can anybody help me with this?

Code implemented by me is

public List<Student> populateData(String fileName) {
    // TODO Auto-generated method stub
    Scanner s = null;
    try {
        s = new Scanner(new File("F:\\Participant_Workspace\\Q3\\StudentDataManagementSystem\\StudentDetails.txt‌​"));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    List<Student> list = new ArrayList<Student>();
    while (s.hasNext()){
        list.addAll(s.next());
    }
    s.close();
    return list;
}

but it gives error to add arrayList<string> and to list.addAll(s.next());.

1 个答案:

答案 0 :(得分:0)

Assuming your file is is something like this.

abc 101

xyz 102

pqr 123

Below Given is a simple example, make alterations and do your stuff.

public class PrintStudentsFromFile {

    public static void main(String[] args) {


     List<Student> students= new PrintStudentsFromFile().populateData("path to text file");


     for (Student student : students) {
            System.out.println(student);
        }
    }
    /**
     * Reads Files and returns a List of Students
     * @param filename
     * @return 
     */
    public List<Student> populateData(String filename){
    Scanner s = null;
    String nameAndRollNumber="";
        try {
            s = new Scanner(new File(filename));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        List<Student> list = new ArrayList<Student>();
        while (s.hasNext()) {
        nameAndRollNumber = s.nextLine();
        String[] nameAndRollNumbers = nameAndRollNumber.split("\\s+");
        String name = nameAndRollNumbers[0];
        String roll = nameAndRollNumbers[1];
        list.add(new Student(name, roll));
        }
        s.close();
        return  list;
    }

}
/**
 * 
 * Student Object , with name and Roll Number Params
 */
class Student{

    String name;
    String rollNumber;

    public Student(String name, String rollNumber) {
        this.name = name;
        this.rollNumber = rollNumber;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRollNumber() {
        return rollNumber;
    }

    public void setRollNumber(String rollNumber) {
        this.rollNumber = rollNumber;
    }

    @Override
    public String toString() {
        return "Name :"+name+"- Roll Number : "+rollNumber;
    }


}