0

For part of my weekly labs/homework I've been asked to process a text file and push it to a database using jdbc. First of all I'm trying to figure out how to split up the individual contents of the file which is structured as follows:

1 Alain A 2 75
2 Michael B 3 85
3 Chen C 1 55
4 Caroline D 2 60
5 Mohamed E 2 60
6 Alex F 1 55
7 Sofia O 3 78
8 Samir O 1 85
9 Rob G 2 78
10 Big K 3 55

The first number is the student id, string is the student name with surname initial, the last two ints are the students year and their mark.

I think once I have divided this input into separate arraylists I can figure out how to push it to the database fairly easily but the trouble I'm having is splitting up the input. I had tried populating 4 separate arraylists by using an incremental counter that chooses which arraylist to push to and resets back to 1 when it goes over 4.

e.g (not proper code):

while (scanner.hasNext()){ 
  if(counter > 4){counter = 1;}
  if (counter == 1){arraylist1.add;}     
  if (counter == 2){arraylist2.add;}   
  if (counter == 3){arraylist3.add;}   
  if (counter == 4){arraylist4.add;}   
  counter++;  
}

This doesn't work which to be honest I fully expected but I don't know how to go about solving this problem. I still want to populate 4 different arraylists so I have the information divided and can still refer to a whole set just by using the same index across the lists.

c.timothy
  • 97
  • 10

1 Answers1

0

Wrong. You do not use several lists to hold that data.

You create one class that represents a row, lets call it the StudentMark class. And that class contains fields for ID, Name, grade, ...

You read the file line by line; and for each line you push the strings into the StudentMark constructor (for example). To be precise: you want to decouple things even more; like having a Parser class that takes a single line from the file input. The parser then splits the input into the fields; and well, parses the expected content (for example using Integer.parseInt() to turn grade strings into real numbers). Then that data is used to create new StudentMark objects; and are then added to a single List<StudentMark>.

One core thing about good OO: you try to create helpful data structures that model the aspects of reality you are dealing with. Using flat lists to keep such "table" data is of course possible; but hey: you choose an object oriented, statically typed programming language. So, to make use of the advantages of that context, you want to avoid using flat lists of lists of strings.

GhostCat
  • 137,827
  • 25
  • 176
  • 248