1

I understand the reason behind this exception and I checked my code multiple times. However, I think my index is within the index bound. Can anyone help me out here? Just a side note: assume the condition for while loop will be satisfied. That is, num is at most 3.

 int suit;
 int num = 0;
 String[] suitList = {"c", "d", "h", "s"};
 for (int i = 0; i < 5; i++){
    while (suitList[num].equals(testHand[i].substring(0,1)) == false){
        num++;
    }            
    suit = num + 1;
 }   
1
  • @Eran I think you are right! Commented Apr 16, 2020 at 7:55

1 Answer 1

1

You should reset num to 0 for each iteration of the for loop:

int suit;
String[] suitList = {"c", "d", "h", "s"};
for (int i = 0; i < 5; i++){
   int num = 0;
   while (suitList[num].equals(testHand[i].substring(0,1)) == false){
       num++;
   }            
   suit = num + 1;
}

Otherwise, it may exceed 3 after the first iteration of the for loop.

BTW, your condition can be improved as follows:

int suit;
String[] suitList = {"c", "d", "h", "s"};
for (int i = 0; i < 5; i++){
   int num = 0;
   while (!testHand[i].startsWith(suitList[num]))) {
       num++;
   }            
   suit = num + 1;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think the code can be a little cleaner if we will not use "assumptions" on the size of the testHand array. What about: for (int i = 0; i < testHand.length; i++) or even for (String hand: testHand)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.