0

I'm trying to make 15 different instances of a polygon with each one having a different radius, starting with 225 and each one being 15 pixels shorter than the other, The second and third fields are the coordinates of where the objects center will be places. I know the [i] doesn't work, and I have read that I should use an array, but i am having trouble implementing it to my code:

public void paintComponent(Graphics g)
{
    Graphics2D g2 = (Graphics2D) g;

    int i;
    int number = 15;
    int radiussize = 225;

    for(i=0;i<=number;i++){
        Shape object[i]= new Shape(radiussize-(i*15),250,300);
        object[i].draw(g2);
    }
}

I want the result to be 15 objects named:

object0, object1, object2...object15.
Ahmad Khan
  • 2,655
  • 19
  • 25

3 Answers3

1

If you want to do it in a loop, you cannot have names for the variables. If you want to store them you should make the array of the objects and create them in this way:

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    int number = 15;
    int radiusSize = 225;

    Shape[] objects = new Shape[number];

    for(int i=0; i<number; i++){
        objects[i] = new Shape(radiuSsize - (i * 15), 250, 300);
        objects[i].draw(g2);
    }
} 
Wojtek
  • 1,288
  • 11
  • 16
0

What is the exact problem you have?

Doesn't the below works?

for(i=0;i<=number;i++){
            Shape object= new Shape(radiussize-(i*15),250,300);
            object.draw(g2);
           }
  • no, that just creates a single object instance. i want 15 different instances... – Voltaren Istanbul Oct 01 '16 at 19:53
  • The loop does create 15 different instances. But as i understand you want these instances to be named differently so as to use in later part of your code. In that case go for array/list – vishu saxena Oct 01 '16 at 20:09
0

I understand that you have an array called object somewhere up there in your code right? If yes then just do this, instead of Shape object[i]=...:

object[i] = new Shape(...

It's basically putting a new Shape object on the i'th position in the array called object. Like I said you need to have that array, if you don't then put this somewhere in your class:

Shape[] object = new Shape[16];

This code is creating an array of Shape object with size 16. If you just want to draw your objects and don't store them anywhere, then do:

new Shape(radiussize-(i*15),250,300).draw(g2);

If you want your variables called object1, object2 etc. - you can't do that, and there is no reason you would need that. Just store them in an array, and reference them by arrayName[indexOfElementYouWant].

Shadov
  • 5,421
  • 2
  • 19
  • 38