Reputation: 1069
Here's the question: Given 2 int values greater than 0, return whichever value is nearest to 21 without going over. Return 0 if they both go over.
blackjack(19, 21) → 21
blackjack(21, 19) → 21
blackjack(19, 22) → 19
What I have so far:
public int blackjack(int a, int b) {
if (a>21 && b>21){
return 0;
}
if (a<21 && b>21){
return a;
}
if (b<21 && a>21){
return b;
}
if (21-a < 21-b){
return a;
}
return b;
}
This question is from codingbat.com, and for all the tests that it shows, this code works, but when it finishes and displays "other tests", this code fails. I suppose there's a certain situation where this wouldn't work, but I can't think of it right now. Any thoughts?
Upvotes: 2
Views: 249
Reputation: 486
public int blackjack(int a, int b) {
// if both a and b are outside the valid range
if (a > 21 && b > 21)
return 0;
// if a is within the valid range but b is not
if (a <= 21 && b > 21)
return a;
// if b is within the valid range but a is not
if (b <= 21 && a > 21)
return b;
// if both a and be are within the valid range
return (a-b >= 0) ? a : b;
// Alternative: return Math.max(a, b); ---as per SimonT in the comment
}
So I guess your issue is that you didn't include 21 in your conditions.
Upvotes: 3
Reputation: 10497
You forgot to specify the =
operation in your condition. Change 2nd and 3rd condition to :
if (a<=21 && b>21){
return a;
}
if (b<=21 && a>21){
return b;
}
Upvotes: 1