samedi 28 novembre 2015

Java Boolean assignment. Boolean variable not setting to true

public void keepDice(int keep){
    for(int i = 0; i<dice.length; i++){
        if(keep == dice[i]){
            keepDie[i] = true;
        }   
        else{
            keepDie[i] = false;
        }
    }
}

dice is an int array, keepDie is a boolean array and I'm passing the method a value of 6. I cannot figure out why it will never assign to true even when a 6 matches a 6 unless 6 appears in the first iteration and then it assigns EVERY element to true instead of just the 6's.

this is output if a 6 appears first:

Testing keepDice(): 
6 3 5 1 6 
T T T T T 

and this is output otherwise:

Testing keepDice(): 
5 3 6 5 5 
F F F F F 

this is my toString() method:

public String toString(){

    String msg = new String("");
    String str = new String("");

    msg += "\n";

    for(int i = 0; i<dice.length;i++)
        msg += dice[i] + " ";

    msg += "\n";

    for(int i = 0; i<dice.length;i++){

        str += String.valueOf(keepDie[i]).toUpperCase();
        msg += str.substring(0, 1) + " ";
    }

    msg += "\n";

    return msg;
}

Aucun commentaire:

Enregistrer un commentaire