BinaryString比较Java初学者

时间:2013-10-20 17:47:00

标签: java

我有当前的代码:

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

无论如何,当我使用二进制字符串的索引进行比较时,我有一个越界错误,因为负整数将比正数更长,任何想法我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我解决了这个问题

个人(){         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);
    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;
    }
    }