在阅读了一本有关机器学习的书之后,我试图用Java编写一个简单的遗传算法,并且偶然发现了基础知识。我没有使用Java练习,因此可能缺少了一些非常简单的东西。

个人

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() {


    }

}


人口

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() {

    }
}


该代码的目的是用随机数填充种群和基因。有人可以看看我的代码,看看我要去哪里哪里吗?

最佳答案

之前

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




pop[j] = new Individual();


数组的元素为null。

关于java - 初学者:在Java中为数组分配值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1566948/

10-11 22:02
查看更多