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

2014/12/10

For loop

hungryjunk hungryjunk

2014/12/10

#
Hi guys, I have an issue with a for loop and a random number. for (int i= 0; i < 10; i++) { if (i == 4) { i=i+0; } else { addObject (new Bom(), i, 5); } } I want to replace the for with a random number between 2 and 9. I can't get it to work with the Greenfoot.getRandomNumber. Thank for reading this and I hope someone can help me.
erdelf erdelf

2014/12/10

#
for (int i= Greenfoot.getRandomNumber(7)+2; i < 10; i++) {
this should work I think
hungryjunk hungryjunk

2014/12/10

#
Erdelf, it doesn't help, I have 10 objects, one of them needs to be removed, the code you give me removes more, but thank for trying to help me.
erdelf erdelf

2014/12/10

#
there is no removeObject call in the code you provided so.. you want to remove just one Object, but it has to be purely random which one ?
hungryjunk hungryjunk

2014/12/10

#
Sort of, I want to place 8 of 9 objects (I don't want to place 9 objects first and then remove one) and it has to be purely random which one. In the code I placed it will always place everything except the 4th one.
erdelf erdelf

2014/12/10

#
Maybe this is what you are searching for
int x = Greenfoot.getRandomNumber(10);
for (int i= 0; i < 10; i++) 
{ 
       if (x != 4) { 
            addObject (new Bom(), i, 5);
      } 
} 
danpost danpost

2014/12/10

#
Try:
int rand = Greenfoot.getRandomNumber(9);
for (int i=0; i<9; i++) if (i != rand) addObject(new Bom(), i, 5);
You need to login to post a reply.