Creating Objects at specified indexes
Hi,
I am trying to add created objects to an ArrayList in a for-loop through indexes. The code below gives me errors when I try compile
Code java:
//Create 4 Question objects...
Question ques1 = new Question("First", 1);
Question ques2 = new Question("First", 2);
Question ques3 = new Question("First", 3);
Question ques4 = new Question("First", 4);
//Create an empty Question ArrayList
ArrayList<Question> list = new ArrayList<Question>();
//for loop through 4 times starting at index 1
for(int i=1; i<=4; i++)
{
//Trying to add each Question object along with the specified index during the loop.
list.add(ques+i);
}
The code outputs: cannot find symbol: variable ques
Could anyone identify the problem?
Thanks
Re: Creating Objects at specified indexes
Quote:
cannot find symbol: variable ques
The compiler can not find a variable named: ques
Where is that variable defined?
Re: Creating Objects at specified indexes
I understand how the compiler cannot find ques, but I used a for loop to add each index to the ques variable (ques+i).
So according to the compiler, wouldn't it look as if the variable is ques1, ques2, etc (where 1, 2, etc are the indexes)?
Do you get where I am trying to get at?
Thanks
Re: Creating Objects at specified indexes
Variable names are defined when you type them into the source code.
If you want to change the contents of a String variable from "ques1" to "ques2" etc then enclose ques in "s like this:
"ques" + 1
You can use those Strings as keys in a Map to allow you to access objects using one of those Strings as the key.
Otherwise define an array with the names of the Question variables.
Re: Creating Objects at specified indexes
Thanks, yea il try that so