1

Пытаюсь заполнить массив public int[] alleles = new int[4]; класса Gene рандомными числами от 0 до result, но при обращении к этому массиву из функции solve() класса Diafant, выдаёт ошибку NullPointerException. Строка, где возникает исключение, помечена в коде.

Класс Gene:

public class Gene {
    public int[] alleles = new int[4];
    int fitness;
    float likelihood;

    // Test for equality.
    public boolean equalOperator(Gene gene) {
        for(int i = 0; i < 4; i++) {
            if (gene.alleles[i] != alleles[i]) {
                return false;
            }
        }
        return true;
    }
}

Класс Diofant:

public class Diofant {
final int MAXPOPULATION = 25;
int ca, cb, cc, cd;   //coefficients
int result;
Gene[] population = new Gene[MAXPOPULATION];  //MaxPopulation

public Diofant(int a, int b, int c, int d, int res) {
    this.ca = a;
    this.cb = b;
    this.cc = c;
    this.cd = d;
    this.result = res;
}

public Gene getGene(int i) {
    return population[i];
}

int solve() {
    int fitness = -1;
    // Generate initial generation
    for(int i = 0; i < MAXPOPULATION; i++) {
        for(int j = 0; j < 4; j++) {
            population[i].alleles[j] = (int) (Math.random() * (result + 1)); //ИСКЛЮЧЕНИЕ ЗДЕСЬ !!!!
        }
    }

    if (fitness == createFitnesses()) {
        return fitness;
    }

    int iterations = 0;   // keep track of the iterations
    while (fitness != 0 || iterations < 50) {
        generateLikelihoods();
        createNewPopulation();
        if (fitness == createFitnesses()) {
            return fitness;
        }
        iterations++;
    }
    return -1;
}
3
  • Ну так логично. Когда ты создаешь массив объектов, они все по умолчанию имеют значение null, а ты пытаешься у этого null взять свойство alleles
    – NarasuOo
    8 апр 2020 в 6:36
  • @NarasuOo как сделать чтобы эти обьекты были не null? 8 апр 2020 в 7:20
  • просто создавай эти экземпляры через new в цикле и вставляй в массив
    – NarasuOo
    8 апр 2020 в 12:22

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.