Previous in Forum: Windows 7 Downgrade to Windows XP   Next in Forum: Light Intensity Software
Close
Close
Close
3 comments
Rate Comments: Nested
Anonymous Poster

Java- Creating New Objects Automatically

01/14/2011 5:56 AM

Hi

I'm a beginner in Java. I know how to create a new object using "new" operator. But a program requires a different number of objects each time program runs.

so can someone please suggest how to implement the following--

Ask user how many objects are required-

Store number of objects required in n

for ( n times) {

create new object;

}

I'm familiar with basic grammar in Java. But please do help me in how to name objects when creating objects "automatically".

Thank you in advance.

Reply
Interested in this topic? By joining CR4 you can "subscribe" to
this discussion and receive notification when new comments are added.
Guru
United Kingdom - Member - Not a New Member Hobbies - Musician - New Member Hobbies - Fishing - New Member

Join Date: May 2006
Location: Reading, Berkshire, UK. Going under cover.
Posts: 9684
Good Answers: 468
#1

Re: Java- Creating New Objects Automatically

01/14/2011 6:48 AM

Confess I don't know the first thing about Java. Can you have arrays of objects? If so, it's pretty trivial to create new object(1) to new object(n).

__________________
"Love justice, you who rule the world" - Dante Alighieri
Reply
Guru

Join Date: Oct 2009
Posts: 1460
Good Answers: 30
#2

Re: Java- Creating New Objects Automatically

01/15/2011 9:33 AM

You can declare arrays of objects without specifying their size when the program starts. Your startup routine (it could be inside a class constructor) includes a line:

MyObject myObjectArray[];

in which the [] signifies that myObjectArray is an array of MyObject objects, but does not specify the size. Your input routine then gets a number from the user and assigns it to the variable n. You can now write the line:

myObjectArray = new MyObject[n]; // instantiates an array of size n

Although the array now exists, the elements of the array are still null objects, and must themselves be instantiated:

for (int index = 0; index < myObjectArray.length; index++)
{
myObjectArray[index] = new MyObject();
}

Good luck.

Reply
Anonymous Poster
#3
In reply to #2

Re: Java- Creating New Objects Automatically

01/18/2011 5:35 AM

Hey,

Thank you so much.. :)

Reply
Reply to Forum Thread 3 comments
Copy to Clipboard

Users who posted comments:

Anonymous Poster (1); JohnDG (1); phph001 (1)

Previous in Forum: Windows 7 Downgrade to Windows XP   Next in Forum: Light Intensity Software

Advertisement