V
V
vitya_brodov2021-02-01 15:40:01
Java
vitya_brodov, 2021-02-01 15:40:01

How to add random objects to List?

Good evening!
I have a Seller class which has:
fields:

private int money = random.nextInt(50)+50;            // Начальное количество денег от 50 до 100 монет
   private int currentWeight = 0;
    private  int maxWeight = 200;                               // максимальный вес 200кг
   private List<Products> boughtProducts = new ArrayList<>();  // купленные товары будет сувать сюда

regular array method Products products:
Products[] products = {
            Products.makeProduct(TypeOfProduct.DRIED_FRUITS,20,13,Quality.NORMAL),
            Products.makeProduct(TypeOfProduct.MEAT,40,7,Quality.NORMAL),
            Products.makeProduct(TypeOfProduct.GRAIN,50,15,Quality.NORMAL),
            Products.makeProduct(TypeOfProduct.FLOUR,50,43,Quality.NORMAL),
            Products.makeProduct(TypeOfProduct.PAINT,10,11,Quality.NORMAL),
    };


and the method that receives gets one of the Products array objects:
// Получаем случайный продукт из массива:
    public Products getRandomProduct() {
        int random = (int) (Math.random() * products.length);
        return products[random];
    }

Question: How can one fill a List (i.e. boughtProducts ) with random products until the
money variable is enough to buy the product (i.e. when the product is bought, then money - products.price() ) or
the currentWeight variable is not equal to maxWeight ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vitya_brodov, 2021-02-01
@vitya_brodov

public  void buyingProducts(){
        while (money > getRandomProduct().getPrice() || currentWeight < maxWeight){
            boughtProducts.add(getRandomProduct());
            money -= getRandomProduct().getPrice();
            currentWeight += getRandomProduct().getWeight();
        }
        System.out.println("Купил товары: ");
        boughtProducts.forEach(System.out::println);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question