BodyBingers BodyBingers - 2 months ago 7
Java Question

How can I use several conditions in a loop to compare different indexes of a string?

so I have this mini-project I'm working for myself on and basically it's a simple method in java for a card game that checks if the string has a flush. Keep in mind I'm a beginner in java(and cardgames/poker...) so I"m new to all of this.

e.g:
the string is ""Kh3h7h8h2s" so the hand is King of hearts, 3 of hearts, 7 of hearts, 8 of hearts, 2 of spades etc. The rank is in the 1st, 3rd, 5th, 7th, 9th index of the string. The string needs to have 5 of the same rank to have a flush

public class CardProblemss {

String hand = "Kh3h7h8h2h";

public boolean hasFlush(String hand) {
String suit1 = Character.toString(hand.charAt(1));
String suit2 = Character.toString(hand.charAt(3));
String suit3 = Character.toString(hand.charAt(5));
String suit4 = Character.toString(hand.charAt(7));
String suit5 = Character.toString(hand.charAt(9));
int flushcounter = 0;

while (true) {
if (suit1.equals(suit2)) {
flushcounter++;
}
else if (suit2.equals(suit3)) {
flushcounter++;
}
else if (suit3.equals(suit4)) {
flushcounter++;
}
else if (suit4.equals(suit5)) {
flushcounter++;
}
System.out.println(flushcounter);
if (flushcounter >= 5) {
return true;
}
else {
return false;
}
}

}


Now I can already tell my code is bleh. But my question is, can I formulate a loop that would basically use the charAt(index) method by itself? Since the rank of the hand is at index 1,3,5,7,9, can I write a loop that would increase the index of this method by 2 every time it's ran? Or is there a more efficient way I can do this?
Thanks alot.

Answer

Would something like this work?

int flushCounter = 0;

char s = hand.charAt(1); // s for suite
for (int i = 3; i < hand.length(); i = i + 2) {
  if (s == hand.charAt(i)) {
    flushCounter++;
  }
}

if (flushCounter >= 5) {
  return true;
} else {
  return false;
}

This way, the only way you'll iterate through the string and then on ever odd value, you'll compare the suite. I'm assuming that you're hand size will always be 3 or more. If you want i to start at 1, you can do that too.

int flushCounter = 0;
char s; // s for suite

for (int i = 1; i < hand.length(); i = i + 2) {
  if (i == 1) {
    s = hand.charAt(1); 
  } else if (s == hand.charAt(i)) {
    flushCounter++;
  }
}

if (flushCounter >= 5) {
  return true;
} else {
  return false;
}

With the latter you have to be careful not to initialize s inside the if statement otherwise it'll go out of scope before you can use it.

Note:

if (flushCounter >= 5) {
  return true;
} else {
  return false;
}

can be reduced to

return flushCounter >= 5;

as it will evaluate the expression and then return the result. The former way is much more verbose. Since you are simply returning the value of the expression, I would argue that the latter is simpler.

Comments