Search code examples
javabluej

How do you make an Arraylist of RandomNumber integers? java


So I am relatively new to the programming scene and I am confused as to why my code doesn't work. I am trying to make an arraylist of flowers and then use a random number generator to create a random number of certain flowers, and store them in the array. In my logic, I thought that I created a variable to store the numbers (ex randomRoses) and stored the number in the array so I could easily print out how many of each flower there is by just calling the arraylist and the position. (ex flowerArray[0] would print out 8 Roses) but sadly it does not.

public class Flower
{

    private int randomRoses;
    private int randomTulips;
    private int randomOrchids;
    public ArrayList <Integer> flowerArray;

    public Flower()
    {
        r = new Random();
        t = new Random();
        o = new Random();
        int randomRoses = (r.nextInt(10) + 0);
        int randomTulips = (t.nextInt(10) + 0);
        int randomOrchids = (o.nextInt(10) + 0);
        flowerArray = new ArrayList<Integer>
    }

    public void add2Array ()
    {
        flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
        flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
        flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
    }

    public void printArray()
    {
        System.out.println(flowerArray[0]);
    }

Solution

  • You can use the same random object, no need to create 3 instances of it for the random integer generation,

    Random r = new Random();
    for (int i = 0; i < 3; i++) {
        flowerArray.add(r.nextInt(10));
    }
    System.out.println(flowerArray);
    

    you can not do flowerArray[0] because you have an arrayList and not an array. you can instead do: flowerArray.get(0) for getting the integer at pos zero