我将继续从电子书“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() {
}
}
}
代码编译成功,但没有输出。我必须添加什么来解决这个问题?
答案 0 :(得分:1)
您确定没有收到任何例外。
您将在下面的行中收到java.lang.NullPointerException
if (cards[i] instanceof DvdMembershipCard)
您尚未将任何对象分配给static Object[] cards;
参数,您将收到Null指针异常。
答案 1 :(得分:1)
你永远不会用元素填充数组。没有instanceof
匹配null
...它只会跳过整个代码(没有任何异常)。
您的代码的另一个缺陷(在第二个区块中),如果card.equals(cards[i])
调用card = cards[i]
,则不会分配新值。