2015-02-08 82 views
2

我目前正在學習如何使用遺傳算法。不過,我的方法compareTo()有困難。這種方法應該比較兩個人之間的適應值。我一直在試圖調用我getFitness()方法,它在compareTo()方法可以使用,但我不斷收到此錯誤無法調用我的方法在數組類型int []

不能對數組類型爲int調用getFitness()[]

我不確定這個錯誤來自哪裏。附件將會是提到的方法和構造函數,我將概述出現這種錯誤的位置。謝謝。

public class Individual implements Comparable<Individual> { 
    Random rand=new Random(); //Initialize random object 
    private int size; //Represents N queens 
    private int[] individual; //Represents the array of possible solutions 

    public Individual(int[] permutation) { 
    individual=permutation; 
    size=individual.length; 
    } 

    public Individual(int size) { 
    this.size=size; 
    individual=Util.getPermutation(size); //Constructs an individual object that is an array of ints 
    } 

    public int getFitness() { 
    //How many queens are attacking each other on the diagonal 
    // 0 Represents the best fitness, this is the solution 

    //Number of possible differences in permutation is found through factorial addition 
    int newSize=0; 
    for (int i=0; i<=size; i++){ 
     newSize+=i; 
    } 
    int fitness=0; 
    int [] xDifference=new int[newSize]; //Array that stores distance between Columns 
    int [] yDifference=new int[newSize]; //Array that stores distance between rows 

    //Calculates the distance between columns and stores them 
    for (int i=0; i<size; i++){ 
     for (int j=i+1; j<size; j++) 
     xDifference[i]=j-i; 
    } 

    //Calculates distance between rows and stores them 
    for (int i=0;i<size;i++){ 
     for (int j=i+1; j<size; j++) 
      yDifference[i]=Math.abs(individual[j]-individual[i]); 
    } 

    //Compares xDifference and yDifference elements, if they are equal that means Queens are attacking 
    for (int i=0; i<size; i++){ 
     if (xDifference[i]==yDifference[i]){ 
     fitness++; 
     } 
    } 

    return fitness; 
    } 

    public int compareTo(Individual other) { 
    int compare; 

    if (individual.getFitness()<other.getFitness()){ //ERROR OCCURS HERE 
     compare=-1; 
    }else if (individual.getFitness()>other.getFitness()){// ERROR HERE 
     compare=1; 
    }else { 
     compare=0; 
    } 

    return compare; 
    } 
} 
+3

'個人'是你的'可能的解決方案'的數組,它是一個'int []'。你想用'this'而不是'individual'。 – EpicPandaForce 2015-02-08 20:16:28

回答

2

問題是您要求individual.getFitness()individual確實是int[],而不是Individual對象。相反,你需要使用

if (this.getFitness()<other.getFitness()){ 
    compare=-1; 
} 

你也可以離開了this.,但我個人認爲它使代碼更易於閱讀。

1

在你compareTo方法您正在訪問的領域individual這是一個數組,而不是一個Individual

相關問題