mercredi 27 janvier 2021

JAVA choose a random object

Hi there im new with Java and i cant find the way to get or choose a random object from my list products.I tried so many different ways but is always giving me an error.

    
public class VendingWorking {
    
    List<Product> products= new ArrayList<>();
    
    
public void registerProducts() {
    CStamp stampOne=new CStamp("1 Jan 2000", "Collectable Stamp");
    CStamp stampTwo=new CStamp("1 Jan 2000", "Collectable Stamp");
    CStamp stampThree=new CStamp("14 Feb 2000", "Collectable Stamp");
    CCoin coinOne= new CCoin("25 Jan 2019", "Collectable coin");
    Ccar carOne= new Ccar(2015, "Tin Car Toy");
    Ccar carTwo= new Ccar(2018, "Tin Car Toy");
        
        products.add(stampOne);
        products.add(stampTwo);
        products.add(stampThree);
        products.add(coinOne);
        products.add(carOne);
        products.add(carTwo);
    
    }
    public void getRandomElement(List<Product> products){ 
        Random random = new Random(); 
        Product index=products.get(random.nextInt(products.size())); 
    } 

    public List<Product> getRegProducts() {
        return products;
    }
}
    



Aucun commentaire:

Enregistrer un commentaire