0

It's a simple program to create an object for Cards (suit and rank). Eclipse debugger pointed the error to line 16 (String s = ranks[this.rank] + " of " + suits[this.suit];).

public class Card 
{
    private int rank;
    private int suit;

    public Card(int rank, int suit) 
    {
        this.rank = rank;
        this.suit = suit;
    }
    public String toString() {
        String[] ranks = {null, "Ace", "2", "3", "4", "5", "6",
                   "7", "8", "9", "10", "Jack", "Queen", "King"};
        String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
        String s = ranks[this.rank] + " of " + suits[this.suit];
        return s;
    }
    public static void main(String args[])
    {
        Card a=new Card(1,11);
        System.out.println(a);
    }
  • 4
    When you see the words 'ArrayIndexOutOfBoundsException', what exactly do you think might have caused the problem? (hint: `new Card(1, 11)` has the numbers backwards, which leads to trying to fetch the 11th index in `suits` which has only 4 elements) – Green Cloak Guy Mar 20 '21 at 04:57

1 Answers1

0

Because in "suits" only four values. Index: 0, 1, 2, 3.