|
-
March 2nd, 2009, 05:24 PM
#1
Quick beginner question
I need some help with a java program. I'm just in a beginners java class, so it's not too hard of a question, I just couldn't find the answers anywhere
I need to create multiple objects of a class which has methods and characteristics for different "problems" of a test. I need to declare many of these objects, yet I don't want about 3 lines repeating about 25 times. I think I can use a for loop to create these objects, but then I couldn't name the objects differently.
For example:
for (int curQuestion = 1; curQuestion < numOfQuestions; curQuestion++);
{
System.out.println ("Enter question" + curQuestion);
Question = scan.nextLine();
System.out.println ("Enter answer for question" + curQuestion);
Answer = scan.nextLine();
q = new Question (question, answer);
quiz.add (q);
}
each time the for loop loops, the entered values are used to create new object questions, which then get added to the next place in the array list. these question objects are all named "q" and I was wondering if that could actually work.
Can I create multiple objects of the same name with different properties to it?
(if there is an easier way, it would kinda have to be simple java; my teacher wouldn't want me using really anything more advanced than that stuff...)
-
March 2nd, 2009, 08:06 PM
#2
Re: Quick beginner question
This works. q is just a temporary reference to each object you allocated in the for loop. You can also allocate memory without declaring any temporary reference:
Code:
quiz.add (new Question(question, answer));
Last edited by Helstorm; March 2nd, 2009 at 08:08 PM.
-
March 7th, 2009, 07:39 AM
#3
Re: Quick beginner question
You cannot create multiple objects with the same name.Here what done is,just rewriting the object with the new..or It is similar to following,,
int a;
for(int i=0,i<10;i++)
a=i;
Here you are not creating the multiple integer variables with the same name...
Last edited by ms_javalover; March 7th, 2009 at 07:40 AM.
Reason: To add some more text
-
March 7th, 2009, 07:41 AM
#4
Re: Quick beginner question
Creating array of objects is also possible...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|