I have three Objects, and a constructor, but i cant figure out how to read in the correct data.

I have an idea, create a count, and then skip lines according to the count. but i have no idea how to put it in code. I have 3 sets of data for 3 different objects. Here is the constructor i'm using.

public StudentRec() throws FileNotFoundException {

    {

        firstname = scan.next();
        lastname = scan.next();
        age = scan.nextInt();

        System.out.println(firstname + " " + lastname + " " + age);
    }

}

Here are the objects.

    StudentRec Student1 = new StudentRec();
    StudentRec Student2 = new StudentRec();
    StudentRec Student3 = new StudentRec();

Of course all it does is read the first line of data and put it in every object. How would I read the first line of the data, then when it's time for the next student, Skip the first line and read in the next line.

The data as you can see is just

Firstname Lastname Age

FirstName Lastname Age

As it appears in the document.

有帮助吗?

解决方案

Move the file reading out of the student recs so that you read the three triplets one after another and create three separate objects in a row.

其他提示

Use a bufferedReader to read each line in the txt file.

  BufferedReader in
       = new BufferedReader(new FileReader("student.txt"));

    String[] studentData = in.readLine().split(" ");

It will read each line from your text file, and split the data based on spaces.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top