0

In the following code I'm getting ArrayIndexOutOfBoundsException. I'm new to Java don't get the clue that is causing it to go out of bounds. I debug this code and it goes terminated after entering 4 entries.

        String[] suit = {"Clubs", "Diamonds", "Hearts", "Spades"};
        String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
        String[] deck = new String[suit.length * rank.length];

        int i = (int)(Math.random()*rank.length);
        int j = (int)(Math.random()*suit.length);

        System.out.println(rank[i]+" of "+suit[j]);         

        for(int k=0; k<suit.length; k++){
            for(int l=0; l<rank.length; l++){
                //on the following line.
                deck[rank.length*k + l] = rank[k]+ " of "+suit[l];
            }
        }

        for(String s : deck){
            System.out.println(s);
        }
LetMeCodeYou
  • 320
  • 1
  • 9

2 Answers2

1

I'm pretty sure you have these variables mixed up

deck[rank.length*k + l] = rank[k]+ " of "+suit[l];

should be

deck[rank.length*k + l] = rank[l]+ " of "+suit[k];
Tah
  • 1,526
  • 14
  • 22
  • It is working fine. Can you please explain it. Just for the sake of getting rid of exception. Answer of Abdelhak also make it correct. His explanation makes sense but not the output. Your solution gives the correct output. – LetMeCodeYou Jan 31 '16 at 09:04
  • 1
    you're using `k` for the index of suits (which you have 4 of) and `l` for the index of ranks (which there are 13). Since you don't have an index > 3 in `rank`, you end up with an `ArrayIndexOutOfBoundsException` – Tah Jan 31 '16 at 09:08
0

The cause of issue is You should use k index instead of l:

   deck[rank.length*k + l] = rank[k]+ " of "+suit[l];

Like this:

    deck[rank.length*k + l] = rank[k]+ " of "+suit[k];

Because the rank.length > suit.length for that there is no data in suit array in this index suit[4].

Abdelhak
  • 8,299
  • 4
  • 22
  • 36