Search code examples
arraysclassobjectbluej

Using Random Objects in Arrays


So i am fairly new to programming but I have the basics like loops and arrays down and now I'm moving on the classes and objects. I want my to get my pet to "eat" and output 3 food elements using an array.

This is my main method

Food[] f = new Food[3];
    for(int i = 0; i < 3; i++){
        f[i] = new Food();
        System.out.println("Your " + pet.type + " ate some " + food.name);
        pet.eat(food);
    }

And I am calling the food from the "Food Class"

public class Food {

int nutrition;  // scale from 0 - 5 where 5 is super nutritious
String name;  // name of food

public Food(){
    Random r = new Random();
    int num = r.nextInt(6);
    if (num == 0){
        name = "rocks";
        nutrition = 0;
    } else if (num == 1){
        name = "seeds";
        nutrition = 1;
    } else if (num == 2){
        name = "chips";
        nutrition = 2;
    } else if (num == 3){
        name = "carrots";
        nutrition = 3;
    } else if (num == 4){
        name = "fish";
        nutrition = 4;
    } else if (num == 5){
        name = "steak";
        nutrition = 5;
    }
}

My problem here is when I try to run the loop above, it outputs 3 of the same foods even though i specified in the food class that I wanted it to generate a random one.

Example Output Your dog ate some chips This food is not nutritious at all... Your dog ate some chips This food is not nutritious at all... Your dog ate some chips This food is not nutritious at all...

Thanks in advance!


Solution

  • Your new Food object is stored in f[i].

    f[i] = new Food();
    

    But your output is coming from food.name.

    System.out.println("Your " + pet.type + " ate some " + food.name);
    

    You need to be printing f[i].name.