开发者

Beginner: Assigning values to arrays in Java

开发者 https://www.devze.com 2022-12-08 18:11 出处:网络
I am 开发者_开发技巧attempting to write a simple Genetic Algorithm in Java after reading a book on Machine Learning and have stumbled on the basics. I\'m out of practice with Java so I\'m probably mis

I am 开发者_开发技巧attempting to write a simple Genetic Algorithm in Java after reading a book on Machine Learning and have stumbled on the basics. I'm out of practice with Java so I'm probably missing something extremely simple.

Individual

public class Individual {

    int n;
    int[] genes = new int[500];
    int fitnessValue;

    public int getFitnessValue() {
        return fitnessValue;
    }

    public void setFitnessValue(int fitnessValue) {
        this.fitnessValue = fitnessValue;
    }

    public int[] getGenes() {
        return genes;
    }

    public void setGenes(int index, int gene) {
        this.genes[index] = gene;
    }

    public int getN() {
        return n;
    }

    public void setN(int n) {
        this.n = n;
    }

    // Constructor
    public Individual() {


    }

}

Population

import java.util.Random;

public class Population {

    public Population() {

    }

    public static void main(String[] args) {
        Random rand = new Random();
        int p = rand.nextInt(10);
        int n = rand.nextInt(10);

        Individual pop[] = new Individual[p];

        System.out.println("P is: " + p + "\nN is: " + n);

        for(int j = 0; j <= p; j++) {
            for(int i = 0; i <= n; i++) {
                pop[j].genes[i] = rand.nextInt(2);
            }
        }
    }

    public void addPopulation() {

    }
}

The aim of this code is to populate the Population and the Genes with a random number. Could someone please take a look at my code to see where I'm going wrong?


before

pop[j].genes[i] = rand.nextInt(2);

add

pop[j] = new Individual();

the elements of the array are null.


I believe you need to initialize pop[j] before doing pop[j].genes[i] = rand.nextInt();

    Individual pop[] = new Individual[p];

This just initializes the array, not the individual elements. Try to put pop[j] = new Individual() between your two loops.


What they said...

Also, do you mean to call your setGenes method, or do you just want to directly access the gene array.


From what I understand of your code I think you need to do this:

for(int j = 0; j <= p; j++) {
    pop[j] = new Individual();
    for(int i = 0; i <= n; i++) {
        pop[j].setGenes(i, rand.nextInt(2));
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消