Answer the question
In order to leave comments, you need to log in
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<>(); // купленные товары будет сувать сюда
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),
};
// Получаем случайный продукт из массива:
public Products getRandomProduct() {
int random = (int) (Math.random() * products.length);
return products[random];
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question