-5

我将继续从电子书“Java 编程简介”中学习。在那本电子书中,我使用了这种方法:

/**
 * This method scans the array of cards in a for loop.
 */
public void getDetialsOfCards() {
    // Declare a local variable.
    MembershipCard card = null;

    // note the use of the instanceof operator
    for (int i = 0; i < noOfCards; i++) {
        if (cards[i] instanceof DvdMembershipCard) {
            card = cards[i];
            System.out.println("This is a DVD card with " + getNoOnLoan()
                    + " DVDs currently on loan.");

        } else if (cards[i] instanceof GameMembershipCard) {

            card = cards[i];
            System.out.println("This is a games card with " +
                    getNoOnLoan() + " CDs currently on loan");

        } else {
            System.out.println("Neither type of card.");

        }
    } // End of for loop.

}

这是我的主要方法:

public class CompundIfElsegetDetialsOfCards {

    // private static int noOfCards = 2;
    private static int NoOnLoan;
    private static Object[] cards;

    private static DvdMembershipCard[] dvd = new DvdMembershipCard[6];
    private static GameMembershipCard[] game = new GameMembershipCard[6];
    private static MembershipCard card;

    public static void getDetialsOfCards() {
        // Declare a local variable.

        int noOfCards = 6;

        // note the use of the instanceof operator
        for (int i = 0; i < noOfCards; i++) {
            if (cards[i] instanceof DvdMembershipCard) {
                card.equals(cards[i]);

                System.out.println("This is a DVD card with " + getNoOnLoan()
                        + " DVDs currently on loan.");

            } else if (cards[i] instanceof GameMembershipCard) {
                card.equals(cards[i]);

                System.out.println("This is a games card with " +
                        getNoOnLoan() + " CDs currently on loan");

            } else {
                System.out.println("Neither type of card.");

            }

        } // End of for loop.

    }

    public static void main(String[] args) {
        CompundIfElsegetDetialsOfCards.getDetialsOfCards();
    }

    private static int getNoOnLoan() {

        System.out.println("jumlah Loan ");
        return NoOnLoan;
    }

    private static class MembershipCard {

        public MembershipCard() {

        }
    }

    private int i;

    private static class DvdMembershipCard {
        public DvdMembershipCard() {

        }
    }

    private static class GameMembershipCard {
        public GameMembershipCard() {

        }
    }
}

代码编译成功,但没有输出。我必须添加什么来解决这个问题?

4

2 回答 2

1

你确定你没有收到任何异常。

您将java.lang.NullPointerException在以下行中收到

if (cards[i] instanceof DvdMembershipCard)

您尚未将任何对象分配给static Object[] cards;参数,您将收到 Null 指针异常。

于 2012-12-12T02:56:00.780 回答
1

你永远不会用元素填充数组。没有instanceof匹配项null......它只会跳过整个代码(没有任何异常)。

您调用的代码的另一个缺陷(在第二个块中)card.equals(cards[i])如果card = cards[i]没有分配新值。

于 2012-12-12T02:57:20.580 回答