0

I'm new to Java, and I can't 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;
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
J.J
  • 1
  • 1

1 Answers1

0

You might want to change the return type of getRandomElement to either return an index or the Product. It's void right now. The other thing would be wary of your class variable names. You use products as a argument for the method.

public int getRandomElement(List<Product> p){ 
  return (int)(Math.random() * (p.size()-1));
}

public Product getRandomElement(List<Product> p){ 
  return p.get((int)(Math.random() * (p.size()-1)));
} 

The first should return a random index the second an object. You might be having an indexing issue if you're scaling off the total list size.

  • 1
    IMHO his use of the Random class is cleaner than the one youre showing. You’re right with the return +1 – Felix Jan 27 '21 at 16:59