Re: Problems generating names for instancevariables in a vector
On May 12, 9:50 am, iMo...@live.se wrote:
Hello guys. I wanted to wright something that filled a vector with
objects of the same type. Sins I don't know how many objects there is
going to be beforehand I wanted some way to generate names for them
when they are created. I tried something like the algorithm below but
it's not working. Any help or suggestions would be welcome and thanks
in advance.
public class Board {
public int numSquares;
Square[] sq = {};
public void mksquares(int k){
The method name does not adhere to the Java naming conventions, which
call for camel case in variable and method names, starting with a
lower-case letter. Also, there is no good reason to be so terse with
the name.
for (int i = 0; i < k; i++){
Square genName("Sq", i) = new Square();=
// "here is
the rub"
This is not legal Java syntax. A variable name must follow the rules,
which do not include parentheses, quotes, commas or spaces.
You can associate a name with an object by including it as an
attribute of the object, or by using a map such as 'Map <String,
Square>', that maps the name to the object. In fact, maps are a
standard way to implement associative arrays in Java.
}
Try something like this (no more complete than the OP code):
private static final String PREFIX = "square";
public Map <String, Square> makeSquares( int k )
{
Map <String, Square> squares = new HashMap <String, Square> ();
for ( int i = 0; i < k; i++ )
{
squares.put( PREFIX + i, new Square() );
}
return squares;
}
--
Lew