Al Hennessey
Al Hennessey

Reputation: 2445

Second for loop not being executed

I have this simple program where I am trying to output all the cards in a deck of cards. However it is only outputting the 1-9 cards of each set, and none of the face cards. i.e. only the for loop with j is being executed, but not the f for loop involving the cardFace array. Why is this?

public class cards {

    public final String cardValue[] = {"Heart", "Diamond", "Spade", "Club"};
    public final String cardFace[] = {"Jack", "Queen", "King", "Ace"};

    public void outputCards() {

        for (int i = 0; i < cardValue.length; i++) {
            int k = 1;

            if (k <= 9) {
                for (int j = 1; j <= 9; j++) {
                    System.out.println("The Card is a " + j + " And is a " + cardValue[i]);
                    k++;
                }
            } else {
                for (int f = 10; f < cardFace.length; f++) {
                    System.out.println("The Card is a " + f + " And is a " + cardValue[i]);
                    k++;
                }
            }
        }
    }
}

Upvotes: 1

Views: 62

Answers (2)

Andres
Andres

Reputation: 10717

 for(int i = 0; i <cardValue.length; i++){
        int k = 1;
        if(k <=9){
        ...

Given the preceding code, it'll always enter on the if and never on the else. Therefore, the for that uses the f variable, will never be executed.

Upvotes: 4

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Even if your code got to the loop it will never run because this for condition will never be true:

for(int f = 10; f < cardFace.length; f++){

If you inspect the cardFace array and get its length, you'll see that it is always less than f.

Most all of your logic is a bit off. I suggest that you write out the program steps on paper first, thinking through the steps before trying to commit it to code, because usually these types mistakes are caused by coding before thinking.

Upvotes: 1

Related Questions