Let there be a Cat constructor (String color). How to create a certain number (even 20) of objects of this constructor (with different names: cat1, cat2, ..., catN) and feed random colors to the input? The rest of the contents of the constructor does not matter, there are constants like the number of paws. Preferably with a for loop. Help to understand please. Maybe it can be done automatically in the constructor as well to set a random color from an array of a constructor previously created in the class? Will it be correct?

//Не судите строго, я только учусь, могу писать какие-нибудь глупости 
  • And what exactly does not work? - MBo
  • I create an array with numbers from 0 to 19 and try to add numbers to the name, but java does not allow it, or I write incorrectly @MBo - Vladislav Estrin

2 answers 2

Enumeration of colors with a static method that produces a random color:

 public enum CatColor { BLACK, WHITE, GREY, RED, BLUE; private static Random random = new Random(); private static int colorsCount = values().length; public static CatColor getRandomColor() { return values()[random.nextInt(colorsCount)]; } } 

Cat class:

 public class Cat { private String name; private CatColor color; public Cat(String name, CatColor color) { this.name = name; this.color = color; } public String getName() { return name; } public CatColor getColor() { return color; } @Override public String toString() { return "Cat " + name + " has color " + color; } } 

main method:

 public static void main(String[] args) { List<Cat> cats = new ArrayList<>(); //создаём котов for (int i = 0; i < 20; i++) { Cat cat = new Cat("cat"+(i+1), CatColor.getRandomColor()); cats.add(cat); } //печатаем котов cats.forEach(System.out::println); } 

Conclusion:

 Cat cat1 has color BLUE Cat cat2 has color WHITE Cat cat3 has color BLACK Cat cat4 has color BLACK Cat cat5 has color RED Cat cat6 has color BLUE Cat cat7 has color WHITE Cat cat8 has color RED Cat cat9 has color WHITE Cat cat10 has color BLUE Cat cat11 has color RED Cat cat12 has color WHITE Cat cat13 has color GREY Cat cat14 has color WHITE Cat cat15 has color BLACK Cat cat16 has color GREY Cat cat17 has color GREY Cat cat18 has color BLACK Cat cat19 has color BLUE Cat cat20 has color BLACK 

    An array of numbers is not needed - there is a loop counter. And add it to the string - for example, using Integer.ToString() (or String.valueOf(number) , or form a complex string using String.format )

     for (int i = 0; i < 20; i++) System.out.println("cat" + Integer.toString(i)); 

    and even works (IMHO, not good for a typed language)

      System.out.println("cat" + i); 

    For colors, a completely random selection may result in very similar colors. If the number of copies is limited, it is reasonable to create an array / list of not very close colors, and randomly choose from it (for example, using one iteration of the Fischer-Yets shuffle)