Search code examples
javaarraysconstruct

Why is this returning a null arraylist?


I want to create two constructors, one that creates a Human with an age and a name, and one that uses the first constructor to create a human with a random age and name.

I create an array of names [Name1, Name2,...,Name9] and pick out a random name, then I create a random age between 1-100 and store it as rage, finally I create a Human with its random name and age.

In my main method, I want to create an arraylist of 9 random Humans and print it out, but I just get 9 Humans with name: null and age: 0. Any help would be greatly appreciated!

class Human {
    int age;
    String name;

    public Human (int myAge, String myName) {
        name = myName;
        age = myAge;
    }

    public Human() {
        ArrayList<String> randomnames = new ArrayList<String>();
        for (int j=1;j<10;j++) {
            randomnames.add("Namn"+j);
        }
        Random randomGenerator = new Random();
        int index = randomGenerator.nextInt(randomnames.size());
        String rname = randomnames.get(index); 

        int rage = (int) (Math.random()*100)

        Human randomPerson = new Human(rage,rname);
    }

    public static void main (String[] args) {

        ArrayList<Object> randomHumans = new ArrayList<Object>();
            for (int j=1;j<10;j++) {
                Human randomPerson = new Human();
                randomHumans.add(randomPerson);
            }
        System.out.println(randomHumans);
    }
}

Solution

  • One solution is to write this(rage,rname) but this only works if it's the first line in the constructor. To make it the first line in the constructor, two functions need to be created first.

    private int randomAge(){
        return randomGenerator.nextInt(100);
    }
    
    private String randomName(){
        return "Namn"+randomGenerator.nextInt(10);
    }
    

    After these two functions are created, the second constructor can say this(randomAge(),randomName()).