class - Using Random Objects in Arrays -


so new programming have basics loops , arrays down , i'm moving on classes , objects. want pet "eat" , output 3 food elements using array.

this main method

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

and calling food "food class"

public class food {  int nutrition;  // scale 0 - 5 5 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 when try run loop above, outputs 3 of same foods though specified in food class wanted generate random one.

example output dog ate chips food not nutritious @ all... dog ate chips food not nutritious @ all... dog ate chips food not nutritious @ all...

thanks in advance!

your new food object stored in f[i].

f[i] = new food(); 

but output coming food.name.

system.out.println("your " + pet.type + " ate " + food.name); 

you need printing f[i].name.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -