mercredi 29 avril 2015

if...else...if executes final else for all conditions

I'm new to Java and trying to do an assignment using the if...else...if statement. Seems simple enough, however, the final "else" statement (the default) executes no matter if the other conditions are true or not. In other words, for all conditions, the code returns 0.

Here's my code:

public class Choice {

private int type; //stores the choice type: 0=rock, 1=paper, 2=scissors
private ColorImage choiceImage; //stores the image to be displayed on the canvas

public Choice(int type)
{
    //initialize the "type" instance varialble
    this.type = type;
}

/**
 * Get a number that represents the choice type
 * 
 * @return  a number that represents the choice type: 0=rock, 1=paper, 2=scissors
 */
public int getType()
{
    return type;
}

/**
 * Compare "this" with anotherChoice
 * 
 * @param   anotherChoice   the choice to be compared
 * @return  either 1, -1, or 0 which indicates the comparison result: 1 means "this" wins anotherChoice; -1 means "this" loses to anotherChoice; 0 means "this" and anotherChoice are the same
 */
public int compareWith(Choice anotherChoice)
{
    if ((this.type == 0) && (type == 1))
        return -1;
    else if (this.type == 0 && type == 2)
        return 1;
    else if (this.type == 1 && type == 0)
       return 1;
    else if (this.type == 1 && type == 2)
       return -1;
    else if (this.type == 2 && type == 0)
       return -1;
    else if (this.type == 2 && type == 1)
       return 1;
    else
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire