DumDum BTC
DumDum BTC

Reputation: 1

adding constants together in a single method with if statements

I am trying to create a single method that adds points if a player meets certain criteria

the base rate for all players is 60

if greater than 74 inches tall and 190 pounds heavy is 5

if scores goals true is 4

if drinks beer true is - 10

I don't know how to add the constants together in a single method but I could do it by creating multiple methods

private String firstName;
private String lastName;
private int height;
private double weight;
private boolean scoresGoal;
private boolean drinksBeer;

public static final int BASE_RATE = 60;
public static final int TALL_INCHES = 74;
public static final double HEAVY_POUNDS = 190.0;
public static final int TALL_HEAVY_BONUS = 5;
public static final int SCORES_BONUS = 4; 
public static final int DRINKS_DEDUCTION = 10;

public int calculateGamePay() {

    return BASE_RATE + getTALL_HEAVY_BONUS() + getSCORES_BONUS() - getDRINKS_DEDUCTION();

}

public int getTALL_HEAVY_BONUS(){

    if(height >= 74 && weight >= 190) { 

       return TALL_HEAVY_BONUS;

    } else{  

       return 0;

    }

}

public int getSCORES_BONUS(){

    if(scoresGoal == true) {

        return SCORES_BONUS;

    } else {

        return 0;

    }

}

public int getDRINKS_DEDUCTION(){

    if(drinksBeer == true) {

        return DRINKS_DEDUCTION;

    } else {

        return 0;

    }

}

Upvotes: 0

Views: 49

Answers (1)

Unmitigated
Unmitigated

Reputation: 89384

You can use three if statements in your calculateGamePay method to add or subtract points from a starting amount of BASE_RATE.

public int calculateGamePay() {
    int pay = BASE_RATE;
    if(height >= 74 && weight >= 190) pay += TALL_HEAVY_BONUS;
    if(scoresGoal) pay += SCORES_BONUS;
    if(drinksBeer) pay -= DRINKS_DEDUCTION;
    return pay;
}

Alternatively, you can combine the logic of all three of your methods into one line using the ternary operator.

public int calculateGamePay() {
    return BASE_RATE + (height >= 74 && weight >= 190 ? TALL_HEAVY_BONUS : 0)
        + (scoresGoal ? SCORES_BONUS : 0) - (drinksBeer ? DRINKS_DEDUCTION: 0);
}

Upvotes: 1

Related Questions