我在主要方法 中寫了這個語句異常將在(GuaranteeYears
)中,所以我把它放在try塊中。catch添加異常
首先在main
我做出Store
對象和參數傳遞號4,在Store
I類將有一個陣列稱爲arrProduct
,將具有長度爲4:
boolean flag1 = true;
while (flag1) {
try {
System.out.println("Ente GuaranteeYears");
int GuaranteeYears=read.nextInt();
StrongDevice s = new StrongDevice(code,type,price,Model,Capacity,GuaranteeYears); //the object
flag1 = false;
x.addProduct(s);
}
,這是我的外接方法
public boolean addProduct(Product p) {
if(arrProduct.length==NumOfProduct)
return false;
arrProduct[NumOfProduct]=p;
NumOfProduct++;
return true;
}
我的問題是:當我做對象,並將其添加到陣列它給了我NullPointerException
- 爲什麼會發生?
@SotiriosDelimanolis我真的知道什麼是空指針異常,但我不知道它爲什麼發生在這裏? – BSMN
NPE沒有一百萬個原因發生。閱讀答案。你會發現它爲什麼會發生,你可以將它應用到你的場景中。 –