0

我有当前的代码:

public class Individual{

    static int DNA_LOWER_DOMAIN = -100;
    static int DNA_UPPER_DOMAIN = 100;


    private double fitness = 0.0;
    private int x_coordinate = 0;
    private String bit_x_coordinate;

    Individual(){
        int number = DNA_LOWER_DOMAIN + (int)(Math.random() * (DNA_UPPER_DOMAIN - DNA_LOWER_DOMAIN) + 1);
        x_coordinate = number;

        bit_x_coordinate = Integer.toBinaryString(x_coordinate);
    }

    public void store_gene(int i, int get_gene) {

        bit_x_coordinate = bit_x_coordinate.replace(bit_x_coordinate.charAt(i),(char) get_gene);

    }
}

调用 store_gene 的函数

private static Individual crossover(Individual inhabitant1, Individual inhabitant2){

    Individual child = new Individual();

    for(int i = 0; i < inhabitant1.size(); i++){

        if(Math.random() <= uniformalRate){

            child.store_gene(i, inhabitant1.get_gene(i));

        }
        else{

            child.store_gene(i, inhabitant2.get_gene(i));
        }


    }

    return child;
}

无论如何,当我使用二进制字符串的索引进行比较时,我有一个越界错误,因为负整数会比正整数长,知道如何解决这个问题吗?

4

2 回答 2

0

ToBinaryString() 不打印前导零。您必须填充字符串。

于 2013-10-20T18:13:14.927 回答
0

我已经解决了这样的问题

Individual(){ int number = DNA_LOWER_DOMAIN + (int)(Math.random() * (DNA_UPPER_DOMAIN - DNA_LOWER_DOMAIN) + 1); x_坐标=数字;

    bit_x_coordinate = Integer.toBinaryString(x_coordinate);
    if(bit_x_coordinate.length() < 32){

    int number_of_bits = bit_x_coordinate.length();

        for(int i = 0; i < (32-number_of_bits); i++){

        bit_x_coordinate = "0" + bit_x_coordinate;
    }
    }
于 2013-10-20T18:48:43.067 回答