0

I am making a bunch of circles with different parameters. Each circle is a separate instance. For example, c1 has a radius equal to 10, x coordinate of 250, etc. I don't know how many circles I will have and it can change. I'm just learning Java, so I don't know how to use a lot of things. I was hoping there was a way to automatically increment the name, so there would be c1, c2, c3, etc.

The way I have it set up is like this:

While(i>=0)
{
Circle c1 = new Circle();
cl.radius = 10;
cl.x = 250;
i--;
}

The numbers (250, 10) aren't set either. Those are randomly generated, so I wouldn't be typing all of that out

user2981333
  • 1
  • 1
  • 1

3 Answers3

0

Use an array, and with each loop store the new Circle in the array. The name of the variable doesn't matter then. Look at this: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html to better understand it :)

Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49
0

Another way would be to use a Map < String, Circle > where the keys are the Strings: "c1", "c2" etc and the values would be the Circles with those names.

NormR
  • 336
  • 3
  • 12
0

First forget about "dynamically changing variable name". This is not going to work in Java.

As mentioned by other, using array is probably what should first learn. However as you have mentioned that number of circles are unknown and can be changed, I believe using a List (ArrayList or LinkedList) can further reduce your trouble.

So you can have a List of Circle, and your code will look like:

List<Circle> circles = new ArrayList<Circle>();

while (i <= 0) {
  Circle circle = new Circle();
  circle.setRadius(i * 10);
  circle.setX(i);
  circles.add(circle);
}
Adrian Shum
  • 38,812
  • 10
  • 83
  • 131