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

2019/6/6

Remove an element from an array

wslade wslade

2019/6/6

#
I am trying to create images in a world. I want to use a list, add an item from the list, then remove the item so it can't be added again. I am trying to use .remove.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)


public class MyBoard extends World
{
    private String[] Images = {"Copper","Lead","Gold", "Carbon","Platinum"};
    
    public MyBoard()
    { 
        super(600, 400, 1);
        
        //set up images
        for(int i=0; i < 5; i++)
        {
              
          
            int x = Greenfoot.getRandomNumber(Images.length);  //count images in array,    
            Cards card = new Cards(Images[x] + ".jpg");//add the image
            addObject(card, 90 + i*125,110);
            Images.remove(x);//then remove element from the array so it can't be placed again
        }
       
    }
}
danpost danpost

2019/6/6

#
You cannot remove an element from an array; you can only change its value. Unlike a List object, arrays have static (immutable) length. You could move the highest indexed value into the slot you chose and decrease the random range:
for (int i=0; i<Images.length; i++)
{
    int x = Greenfoot.getRandomNumber(Images.length-i);
    Cards card = new Card(Images[x]+".jpg");
    addObject(card, 90+i*125, 110);
    Images[x] = Images[Images.length-1-i];
}
Or, you could just shuffle the cards and deal them out:
java.util.Collections.shuffle(java.util.Arrays.asList(Images));
for (int i=0; i<Images.length; i++) addObject(new Card(Images[i]+".jpg"), 90+i*125, 110);
wslade wslade

2019/6/6

#
Thanks! That makes sense. Shuffling worked even better than what I was doing.
You need to login to post a reply.