This site requires JavaScript, please enable it in your browser!
Greenfoot back
GreenMan15
GreenMan15 wrote ...

2016/3/4

Placing Objects in a World using a loop

GreenMan15 GreenMan15

2016/3/4

#
Hello I had a quick question. I want add objects of a bubble placed diagonal. My first bubble must have x and y start at (0,0) then (30,30), (60,60) and so on and then finish at (600,600). I only need 21 bubbles to do this and need to use a while loop. My problem is when I compile they are either bunched in one group or my screen stays frozen and it says I may have an infinite loop. Any advice would be appreciated. FYI those parentheses are meant to be brackets but it wouldnt show on the screen when I posted. Bubble() bubble = new Bubble(21); int i =0; while (i < bubble.length) { bubble(i) = new Bubble(); addObject(bubble(i), 0, 0); i = i + 30; } 2nd attempt: Bubble() bubble = new Bubble(21); int i =0; while (i < bubble.length) { bubble(i) = new Bubble(); addObject(bubble(i)+30, 0, 0); i = i +1; }
Super_Hippo Super_Hippo

2016/3/4

#
You need use the 'code' tags. See the link below. For your problem. You add all objects to (0,0). What you want to do is this:
int i = 0;
while (i < 21)
{
    addObject(new Bubble(), i*30, i*30);
    i++;
}
Or, if you need the array:
Bubble[] bubble = new Bubble[21];
int i = 0;
while (i < bubble.length)
{
    bubble[i] = new Bubble();
    addObject(bubble[i], i*30, i*30);
    i++;
}
In your first attempt, you only add one bubble because after this, i is 30 and the loop condition is not true anymore. And in the second, I don't know what 'bubble(i)+30' should be, but the two 0 after that add all bubbles to the top left corner.
GreenMan15 GreenMan15

2016/3/4

#
Oh my gosh Thank you so MUCH! Been working all morning on this and could not for the life of me understand what I did wrong. The explanation made perfect sense to me.
You need to login to post a reply.