user2818700
user2818700

Reputation: 23

Scanning text file into array of objects

I have a comma separated text file with information in the format:

firstname,lastname,meal1,meal2,meal3,meal4 ....with each new student on a new line.

I have the following student object.

public class Student {
    private String first = null;
    private String last = null;

    public Student (String first, String last){
        this.first = first;
        this.last = last;
    }

I need a method that is to be used from another class to populate an Array of student objects.

I am unsure how to do this with the Scanner as I only need the first two from each line, any help pointing me in the right direction would be very thankful.

~Thanks!

Upvotes: 2

Views: 12048

Answers (2)

nkukhar
nkukhar

Reputation: 2025

As a tip I can post you the code how to read lines from file with scanner. Then you can parse a line. Try to do this by yourself. Good luck.

    Scanner s = null;
    try {
        s = new Scanner(new BufferedInputStream(new FileInputStream("Somefile.txt")));
        while (s.hasNextLine()){
            String line = s.nextLine(); //String line representation from file 
    } finally {
        if (s != null) s.close();
    }

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

  try {
        File file = new File("input.txt");
        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {                
            String line = scanner.nextLine();
            String array[] = line.split(",");
            Student student  = new Student (array[0],array[1]);
            -------------------------
            -------------------------
            System.out.println("FirstName:"+ array[0]);
            System.out.println("LastName:"+ array[1]);
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

Upvotes: 5

Related Questions