473,609 Members | 2,263 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterating through a CSV file to create unique array objects?

Ispep
4 New Member
Hi, unfortunately having a bit of difficulty with a question from an Open University course I'm currently doing. If you could help me out in any way I'd be grafeul (though obviously it goes without saying I'm not asking you to solve the question - that won't help come exam time :().

Anyway I have a CSV delimited file in the following format;

Expand|Select|Wrap|Line Numbers
  1. STRING,INT
  2. STRING,INT,INT,INT,INT,INT
  3. STRING,INT,INT,INT,INT,INT
  4. STRING,INT,INT,INT,INT,INT
  5. [...]
The first two values relate to the league name and the number of teams in the league. The rest of the lines relate to the individual teams; their names, games won, drawn, lost, goals for and against.

The class method I'm writing; loadLeague() prompts the user for the text file of this csv, and after which (using BufferedReader and Scanner) reads the information from the first line to create a new League object as so;

Expand|Select|Wrap|Line Numbers
  1. public static League loadLeague()
  2.    {
  3.       League theLeague = null;
  4.       // to be completed by student
  5.       String pathname = OUFileChooser.getFilename();
  6.       File aFile = new File(pathname);
  7.       Scanner bufferedScanner = null;
  8.  
  9.       try
  10.       {
  11.       String leaguesName;
  12.       int numberOfTeams;
  13.       Scanner lineScanner;
  14.       String currentLine;
  15.  
  16.       bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
  17.  
  18.       currentLine = bufferedScanner.nextLine();
  19.       lineScanner = new Scanner(currentLine);
  20.       lineScanner.useDelimiter(",");
  21.  
  22.       leaguesName = lineScanner.next();
  23.       numberOfTeams = lineScanner.nextInt();
  24.       League League = new League(leaguesName,numberOfTeams);
     }
  25.       catch (Exception anException)
  26.       {
  27.          System.out.println("Error " + anException);
  28.       }
  29.       finally
  30.       {
  31.  
  32.       }
  33.  
  34.       return theLeague;
     }

*From line 5 onwards this is 'my' code.

The first String as I say is the name of the league, and the second is the number of teams. These values are passed as an argument to a private constructor League(String,I nt) which aside from creating the League object creates a new (declared private) Teams array;

Expand|Select|Wrap|Line Numbers
  1. this.teams = new Team[size];
...to reference the Teams I'm expected to create and initialise - which is where I am having problems. I'm assuming I have to iterate in order to do this but how do I create dynamic variable names?

As an example of the (twisted) logic I've tried to apply;

Whilst File hasNextLine()
Store each next() and nextInt() value to temporary variables.
create new Team object
using public setters change Team objects values (won,drawn... ect)

This is the code I'm using to create the Team object;
Expand|Select|Wrap|Line Numbers
  1. Team myteam = new Team(theTeamsName);
I haven't got as far as to adding it to the Teams array yet as I can't get around the problem of unique names for each object? if I try;
Expand|Select|Wrap|Line Numbers
  1. Team theTeamsName = new Team(theTeamsName);
for example, it won't work as it's assigning the latter half to the variable (which is a String).

Is there any quick way around this? I mean surely there is a way for Java to understand I just want the contents of 'theTeamsName' and not the variable itself? That way I'm assuming that I can just access the Teams array and manipulate the referenced object by using setters?

Here is just one of my lame, half-assed, unfinished attempts to get around the problem, so see if you could tell me where I've gone wrong.

Expand|Select|Wrap|Line Numbers
  1. while (bufferedScanner.hasNextLine())
  2.        {       
  3.           currentLine = bufferedScanner.nextLine();
  4.           lineScanner = new Scanner(currentLine);
  5.           lineScanner.useDelimiter(",");
  6.  
  7.           tempTeamName = lineScanner.next();
  8.           won = lineScanner.nextInt();
  9.           drawn = lineScanner.nextInt();
  10.           lost = lineScanner.nextInt();
  11.           goalsFor = lineScanner.nextInt();
  12.           goalsAgainst = lineScanner.nextInt();
  13.           Team theTeam = new Team(tempTeamName);
  14.         }
Obviously I declared the variables earlier on (not shown). I believe this works (to the extent no error on processing) but obviously I can't tell yet and I'm not actually using any of the variables apart from teamName, which I could probably have done directly with just 'new Team(lineScanne r.next());' right?

Just a fresh direction for me would be good. I'm lost on this!
May 16 '07 #1
4 3818
JosAH
11,448 Recognized Expert MVP
Why don't you simply create a Team constructor that takes all the significant
parameters at once? Something like this:
Expand|Select|Wrap|Line Numbers
  1. public class Team {
  2.    private String name;
  3.    private int win;
  4.    private int lose;
  5.    private int draw;
  6.    private int gFor;
  7.    private int gAgainst;
  8.  
  9.    public Team(String name, int win, int lose, int draw, int gFor, int gAgainst) {
  10.       this.name= name;
  11.       this.win = win;
  12.       this.lose= lose;
  13.       this.draw= draw;
  14.       // etc.
  15.    }
  16.    ...
  17. }
In your leage class you read those six values using a scanner and construct
a next Team which you stick in your array:
Expand|Select|Wrap|Line Numbers
  1. for (int i= 0; i < teams; i++) {
  2.    String name= scanner.next();
  3.    int win = scanner.nextInt();
  4.    // etc.
  5.    teams[i]= new Team(name, win, lose, draw, gFor, gAgainst);
  6. }
kind regards,

Jos
May 16 '07 #2
Ispep
4 New Member
That would be great, but you aren't allowed to alter existing code, only add your own. The assignments are very much for learning a particular topic so it's quite strict.

Why don't you simply create a Team constructor that takes all the significant
parameters at once? Something like this:
Expand|Select|Wrap|Line Numbers
  1. public class Team {
  2.    private String name;
  3.    private int win;
  4.    private int lose;
  5.    private int draw;
  6.    private int gFor;
  7.    private int gAgainst;
  8.  
  9.    public Team(String name, int win, int lose, int draw, int gFor, int gAgainst) {
  10.       this.name= name;
  11.       this.win = win;
  12.       this.lose= lose;
  13.       this.draw= draw;
  14.       // etc.
  15.    }
  16.    ...
  17. }
In your leage class you read those six values using a scanner and construct
a next Team which you stick in your array:
Expand|Select|Wrap|Line Numbers
  1. for (int i= 0; i < teams; i++) {
  2.    String name= scanner.next();
  3.    int win = scanner.nextInt();
  4.    // etc.
  5.    teams[i]= new Team(name, win, lose, draw, gFor, gAgainst);
  6. }
kind regards,

Jos
May 16 '07 #3
JosAH
11,448 Recognized Expert MVP
Well, use those explicit mutators then:
Expand|Select|Wrap|Line Numbers
  1.  
  2. for (int i= 0; i < teams; i++) {
  3.    String name= scanner.next();
  4.    int win = scanner.nextInt();
  5.    // etc.
  6.    teams[i]= new Team(name);
  7.    teams[i].setWin(win);
  8.    teams[i].setLose(lose);
  9.    teams[i].setDraw(draw);
  10.    // etc.etc.
  11. }
Is that allowed?

kind regards,

Jos
May 16 '07 #4
Ispep
4 New Member
Well, use those explicit mutators then:
Expand|Select|Wrap|Line Numbers
  1.  
  2. for (int i= 0; i < teams; i++) {
  3.    String name= scanner.next();
  4.    int win = scanner.nextInt();
  5.    // etc.
  6.    teams[i]= new Team(name);
  7.    teams[i].setWin(win);
  8.    teams[i].setLose(lose);
  9.    teams[i].setDraw(draw);
  10.    // etc.etc.
  11. }
Is that allowed?

kind regards,

Jos
Absolutely, in fact, that is what I had always intended but my Java knowledge must be so sloppy I didn't realise/remember you can assign objects to index references in the array. That takes care of the dynamic variable name, thanks a lot :)

My problem now is that I can't directly access the teams array because it's not static. So I create a new teams array like such (within loadLeague()); Team[] teams = new Team[numberOfTeams];

but even though the creation of this works within the Try block (println's confirm this) once the method is completed the League objects Teams array is empty. It has the correct size, but each entry is null

I'm guessing this is something to do with try blocks and/or static/non-static methods. I'm hoping someone can point me in the right direction?
May 16 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

1
2908
by: DJTB | last post by:
zodb-dev@zope.org] Hi, I'm having problems storing large amounts of objects in a ZODB. After committing changes to the database, elements are not cleared from memory. Since the number of objects I'd like to store in the ZODB is too large to fit in RAM, my program gets killed with signal 11 or signal 9... Below a minimal working (or actually: it doesn't work because of memory
34
4168
by: Christopher Benson-Manica | last post by:
If an array is sparse, say something like var foo=; foo=4; foo='baz'; foo='moo'; is there a way to iterate through the entire array? --
14
14294
by: vince | last post by:
Can I add (append) to an xml file that already contains a serialized object, and be able to deserialize to either or both objects from the same file...??? How is this done...?? thanks, vince
6
6042
by: Gustaf Liljegren | last post by:
I ran into this problem today: I got an array with Account objects. I need to iterate through this array to supplement the accounts in the array with more data. But the compiler complains when I try to modify the objects in the array while iterating through it. I marked the bugs in this code: // Loop through all previously added accounts foreach(Account a in a1) // a1 is an ArrayList { // If name and context is the same if(a.Name ==...
11
3597
by: hoopsho | last post by:
Hi Everyone, I am trying to write a program that does a few things very fast and with efficient use of memory... a) I need to parse a space-delimited file that is really large, upwards fo a million lines. b) I need to store the contents into a unique hash. c) I need to then sort the data on a specific field. d) I need to pull out certain fields and report them to the user.
0
3926
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen. It is almost like it is trying to implement it's own COM interfaces... below is the header, and a link to the dll+code: Zip file with header, example, and DLL:...
3
2734
by: pbali | last post by:
Hi, I am using PHP 5.1 and MySQL. I have a result set obtained by executing PDO:: query. I want to create an XML file by using this result set. The XML file will contain column names as XML node name and column values as node values. $orders = $db->query($sql); if (!empty($orders)) {
4
2811
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the script a JSON list of any size, and the script will create multiple DOM elements with as many attributes...
7
7143
Curtis Rutland
by: Curtis Rutland | last post by:
Building A Silverlight (2.0) Multi-File Uploader All source code is C#. VB.NET source is coming soon. Note: This project requires Visual Studio 2008 SP1 or Visual Web Developer 2008 SP1 and Silverlight 2.0. To get these tools please visit this page Get Started : The Official Microsoft Silverlight Site and follow Step 1. Occasionally you find the need to have users upload multiple files at once. You could use multiple FileUpload...
0
8121
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8062
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8559
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8386
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6987
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6050
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5506
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4068
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1378
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.