I am currently teaching myself java, and one of the practice problem's final output needs different name for different objects (which is decided based on random number generator). However, every time I create object, those object ends up having same name. To give a clear example, following is the sample output:
and following is my output:
As highlighted in my output, all of my animals have same name while the expected output have different names. I've tested multiple times and can confirm that this is not due to some luck.
My code for Cow
class, which constructs name & other information, is following (I've omitted irrelevant methods):
import java.lang.Math;
import java.util.Random;
public class Cow implements Milkable, Alive {
private String name;
private double capacity;
private double amount;
private static final String[] NAMES = new String[]{
"Anu", "Arpa", "Essi", "Heluna", "Hely",
"Hento", "Hilke", "Hilsu", "Hymy", "Ihq", "Ilme", "Ilo",
"Jaana", "Jami", "Jatta", "Laku", "Liekki",
"Mainikki", "Mella", "Mimmi", "Naatti",
"Nina", "Nyytti", "Papu", "Pullukka", "Pulu",
"Rima", "Soma", "Sylkki", "Valpu", "Virpi"};
private static final String randName = NAMES[new Random().nextInt(NAMES.length)];
// Default Constructor <- where issue is
public Cow(){
this(randName);
}
// Overloaded Constructor
public Cow(String name){
this.name = name;
this.capacity = (15.0 + new Random().nextInt(26));
this.amount = 0.0;
}
// accessors...
// milk... removes milk from cow's tank (implements Milkable interface)
// liveHour... adds milk to cow's tank (implements Alive interface)
// toString...
}
In addition, this is my main class that uses above (again, omitted unnecessary parts):
Farm farm = new Farm("Esko", new Barn(new BulkTank()));
farm.addCow(new Cow());
farm.addCow(new Cow());
farm.addCow(new Cow());
System.out.println(farm);
This post indicates that random number generator ends up being deterministic if there is a seed already set on constructor. However, my random number generator has to have a specific seed (length of array containing random names in this case) in order to choose random name. I was wondering if anyone knows a way around to make my random number generator to produce new values. Thank you in advance.