无法在数组类型int []上调用我的方法

时间:2015-02-08 20:13:13

标签: java object methods

我目前正在学习如何使用遗传算法。但是,我的方法compareTo()有问题。该方法应比较两个人之间的适应度值。我一直在尝试调用我的getFitness()方法,以便在compareTo()方法中使用它,但我一直收到此错误

  

无法在数组类型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;
  }
}

2 个答案:

答案 0 :(得分:2)

问题在于您正在呼叫individual.getFitness()individual确实是int[],而不是Individual对象。相反,你会想要使用

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

你也可以省略this.,但我个人觉得它让代码更容易阅读。

答案 1 :(得分:1)

在您的compareTo方法中,您正在访问字段individual这是一个数组,而不是Individual