I wrote this to generate random Candidate
objects to fill the ArrayList pop
. Each Candidate
holds an array, and this code its supposed to generate a different array for each Candidate
:
ArrayList<Candidate> pop = new ArrayList<>();
int skinThicknes, attackDamage ,skinCoulor, canFly, canSwing, speed, flySpeed, swingSpeed, num = 0;
Random rnd;
rnd = new Random();
while(num < size) {
skinThicknes = rnd.nextInt(101);
attackDamage = rnd.nextInt(101);
skinCoulor = rnd.nextInt(3);
canFly = rnd.nextInt(1);
canSwing = rnd.nextInt(1);
speed = rnd.nextInt(1001);
flySpeed = rnd.nextInt(1001);
swingSpeed = rnd.nextInt(1001);
if(canFly == 0){flySpeed = 0;}
if(canSwing == 0){swingSpeed = 0;}
int[] array = {skinThicknes, attackDamage, skinCoulor, canFly, canSwing, speed, flySpeed, swingSpeed};
Candidate can;
can = new Candidate(array);
pop.add(can);
num++;
}
return pop;
Why are the arrays of every Candidate
in pop
equal?
This is the constructor for Candidate
. All those variables ( skinTicknes
, attackDamage
, etc.) are private static int
s.
public Candidate(int[] geno){
skinTicknes = geno[0];
attackDamage = geno[1];
skinCoulor = geno[2];
canFly = geno[3];
canSwing = geno[4];
speed = geno[5];
flySpeed = geno[6];
swingSpeed = geno[7];
}
If you read the API you'll note that rnd.nextInt(1)
will always return zero (0). This means your canFly
and canSwing
values will always be the same, which in turn means your flySpeed
and swingSpeed
will always be the same.
After that, I think we need to see the definition of Candidate
to see why the rest is always the same. What makes you believe all the elements of the ArrayList
are the same? Can you show us the code for this too?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.