This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Dynamically create objects from a text file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Dynamically create objects from a text file" Watch "Dynamically create objects from a text file" New topic
Author

Dynamically create objects from a text file

Mervin Chan
Greenhorn

Joined: Dec 03, 2004
Posts: 24
How to i create objects dynamically,

Say i need to create x number of "Machine" Objects.

This is the way i create 1 machine object.

Machine a;

Machine a = new Machine (....constructor... )


Say i want to program such that i create x machine objects, the x is unknown at compile time, but is stored in a text file.

Assuming i have read the x value from the text file, how do i create x machine objects?

I want the objects to be named a1, a2, a3... ax,
ie.

for (i=0;i<x;i++)
{
Machine ax? //How?>???

Machine ax = new Machine(...) ///???
}

Any ideas? I'm stumped.

Thanks!

Mervin
Raj Chila
Ranch Hand

Joined: Mar 18, 2004
Posts: 128

Hi you could declare an Array of Machine Type at compile time and assign the array length at run time after reading the file...so you are almost at the right path...all you need is the following...extralines of code.


Machine[] aDynArray;
// you read the x from the file...
aDynArray = new Machine[x]; //place Holder for x number of objects.
for (i=0;i<x;i++)
{
// you dont need this line.Machine ax? //How?>???

//Machine ax = new Machine(...) ///???

//all you need is this
aDynArray[i] = new Machine(...);
}
hope this helps..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Dynamically create objects from a text file