Having trouble checking if a poker hand is a straight. Realized my code wouldn\'
ID: 3774603 • Letter: H
Question
Having trouble checking if a poker hand is a straight. Realized my code wouldn't work since it doesn't check if the ranks increase by an increment of 1. How can I modify this? Thanks.
public static boolean isStraight(){
int c = 0;
for (int i = 0; i < hand.size() - 1; i++){
Card c1 = getCard(i);
Card c2 = getCard(i + 1);
if (c1.getRank().compareTo(c2.getRank()) < 0) {
c++;
}
if (c == 4){
return true;
}
}
return false;
}
Explanation / Answer
public static boolean isStraight( Card[] h ) { int i, testRank; if ( h.length != 5 ) return(false); sortByRank(h); // Sort the poker hand by the rank of each card /* =========================== Check if hand has an Ace =========================== */ if ( h[4].rank() == 14 ) { /* ================================= Check straight using an Ace ================================= */ boolean a = h[0].rank() == 2 && h[1].rank() == 3 && h[2].rank() == 4 && h[3].rank() == 5 ; boolean b = h[0].rank() == 10 && h[1].rank() == 11 && h[2].rank() == 12 && h[3].rank() == 13 ; return ( a || b ); } else { /* =========================================== General case: check for increasing values =========================================== */ testRank = h[0].rank() + 1; for ( i = 1; i < 5; i++ ) { if ( h[i].rank() != testRank ) return(false); // Straight failed... testRank++; // Next card in hand } return(true); // Straight found ! } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.