3

I am trying to write a recursive method that prints out each index of an array. My Hand class represents a hand of five cards, using a Card[] cards of length 5. Below is my method so far. It works but is there a better way to do this instead of having an integer parameter of the index to start from? Please help.

public static void printHandForward (Hand hand, int index) {
    if(index == hand.cards.length) {
        return;
    }
    else {
        Card.printCard(hand.cards[index]);
        index++;
        printHandForward(hand, index);
    }
}
3
  • You could just not have it be recursive. Commented Dec 9, 2015 at 23:24
  • A better way would be to use an enhanced for statement rather than recursion. Commented Dec 9, 2015 at 23:25
  • So you are calling this method and passing in the first index? Commented Dec 9, 2015 at 23:25

2 Answers 2

1

If you must use recursion, you have to call this method with an int parameter somehow.

You can simply add an overload which just takes Hand, which calls your current method:

public static void printHandForward(Hand hand) {
  printHandForward(hand, 0);
}

However, avoiding recusion and just using an enhanced for statement would be much easier.

Sign up to request clarification or add additional context in comments.

2 Comments

@vishalgajera Do you understand what is meant by an overload?
@vishalgajera your comment does not parse in English.
0

Why you need a recursive method, and you couldn't use just:

public static void printHandForward (Hand hand) {
    for(Card card: hand.cards) {
        Card.printCard(card);
    }
}

?

If you really need a recursive method, I recommend use a following code:

printHandForward(hand, hand.length);
...
public static void printHandForward (Hand hand, int index) {
    if(index > -1) {
       printHandForward(hand, index -1);
       Card.printCard(hand.cards[index]);
    }
}

Comments

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.