Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covering all scenarios with if statement

I'm doing the below homework exercise:

Given 2 int values greater than 0, return whichever value is nearest to 21 without going over. Return 0 if they both go over.

I've made the below code:

public static void main(String[] args) {
    System.out.println(blackjack(22,22));
    System.out.println(blackjack(25,25));
    System.out.println(blackjack(19,25));
    System.out.println(blackjack(25,19));
    System.out.println(blackjack(10,10));
    System.out.println(blackjack(19,10));
    System.out.println(blackjack(1,19));
}

// Create a method like:
public static int blackjack(int a, int b) {
    if (a > 21 && b > 21) {
        return 0;
    }
    else if (a <= 21 || b > 21) {
        return a;
    }
    else if (a > 21 || b <= 21) {
        return b;
    }
    else if (a >= b) {
        return a;
    }
    else {
        return b;
    }
}

All of it works except the last line of output in my main. I keep getting "a" or, "1" in this case, so I'm not sure what is wrong with my last line in my method declaration. I have a feeling something is wrong but I'm not sure what to change.

like image 569
Kenneth Yong Avatar asked Dec 19 '22 08:12

Kenneth Yong


1 Answers

You could also avoid some of those if-statements if you instead rely on some mathematical operations:

private static final int TARGET = 21;
public static void main (String[] args) throws java.lang.Exception {
    System.out.println(blackjack(22,22)); //  0
    System.out.println(blackjack(25,25)); //  0
    System.out.println(blackjack(19,25)); // 19
    System.out.println(blackjack(25,19)); // 19
    System.out.println(blackjack(10,10)); // 10
    System.out.println(blackjack(19,10)); // 19
    System.out.println(blackjack(1,19));  // 19
}

public static int blackjack(int a, int b) {
    if ( a > TARGET && b > TARGET) {
        return 0;
    }

    return Math.abs(a - TARGET) < Math.abs(b - TARGET) 
       ? a 
       : b;
}

Note: This works here because 21 is nowhere close to the MAX_INT boundary; if it were overflow would be an issue. Here this article, subtraction is not comparison, for more information if you're interested.

Working example on Ideone

like image 73
Hunter McMillen Avatar answered Jan 07 '23 14:01

Hunter McMillen