2009-10-14 67 views
0

我正在嘗試在閱讀一本關於機器學習的書後,用Java編寫一個簡單的遺傳算法,並且偶然發現了一些基礎知識。我不熟悉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() { 

    } 
} 

此代碼的目的是填充人口和用隨機數的基因。有人可以看看我的代碼,看看我哪裏出錯了嗎?

+2

呵呵。我剛剛在同一個問題中讀過「初學者」和「遺傳算法」。 – 2009-10-14 15:10:38

+1

什麼問題?你預計會發生什麼? – Mark 2009-10-14 15:11:25

+0

你目前正在做的是填充隨機數量的個人隨機部分的基因。你得到了什麼結果,你期望什麼? – msparer 2009-10-14 15:14:30

回答

4

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

之前添加

pop[j] = new Individual(); 

的數組元素爲空。

+0

這個答案有效。謝謝您的幫助! – 2009-10-14 15:17:03

0

我相信你需要在pop [j] .genes [i] = rand.nextInt()之前初始化pop [j];

Individual pop[] = new Individual[p]; 

這只是初始化數組,而不是個別的元件。嘗試在兩個循環之間放置pop [j] = new Individual()。

+0

你應該通過訪問器方法(比如getGenes())而不是直接訪問(.genes)來真正訪問對象屬性。 – stian 2009-10-14 15:15:30

0

他們說什麼......

另外,你的意思是叫你setGenes方法,或者你只是想直接訪問基因陣列。

0

從我理解你的代碼,我想你需要做的:

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)); 
    } 
}