超越界限

时间:2018-11-21 14:36:15

标签: java indexoutofboundsexception

我不确定为什么我会无所事事,有人可以帮忙吗,这真的让我很烦,因为我真的很想了解发生了什么事。

公共类LoyaltyCardList {     私有ArrayList会员卡;

/**
 * 
 */
public LoyaltyCardList()
{
    loyaltyCards = new ArrayList <LoyaltyCard> ();
}

/**
 * 
 */
public void addLoyaltyCard(LoyaltyCard newLoyaltyCard)
{
    loyaltyCards.add(newLoyaltyCard);
}

public void getAllLoyaltyCards()
{
    int index = 0;
    while(index <= getNumberOfLoyaltyCards())
    {
        loyaltyCards.get(index).printCustomerDetails();
        index++;
    }
}

public void getLoyaltyCard(int LoyaltyCardEntry)
{
    if(LoyaltyCardEntry < 0)
    {
        System.out.println("Negative Entry: " +LoyaltyCardEntry);
    }
    else if(LoyaltyCardEntry < getNumberOfLoyaltyCards())
    {
        loyaltyCards.get(LoyaltyCardEntry).printCustomerDetails();
    }
    else
    {
        System.out.println("No Such Entry:" + LoyaltyCardEntry);
    }
}

public int getNumberOfLoyaltyCards()
{
    return loyaltyCards.size();
}

2 个答案:

答案 0 :(得分:2)

您将打印出LoyaltyCards类,而不是loyaltyCard实例

for ( LoyaltyCard loyaltyCard : LoyaltyCards)
{
    System.out.println(loyaltyCard);
}

您还应该确保在LoyaltyCard类中具有适当的toString()覆盖,否则它可能不会转换为所需的格式

答案 1 :(得分:1)

更改

System.out.println(LoyaltyCards);

System.out.println(loyaltyCard);

此刻,您正在尝试打印列表本身。