This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread 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 Android Security Essentials Live Lessons this week in the Android 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..
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Dynamically create objects from a text file
 
Similar Threads
Save File on Client Machine
h:panelGrid with Attribute value
dynamically creating a text box
How to create multiple objects dynamically
How to create the unique file name?