2013-11-03 162 views
-3

我沒有問題,但是在編譯時我執行的代碼我得到這個錯誤:異常線程「main」顯示java.lang.NullPointerException(

Exception in thread "main" java.lang.NullPointerException 
at Stock.enregistrer(Stock.java:25) 
at TestStock.main(TestStock.java:13) 

我學習java,我stucked這個錯誤現在一會兒感謝您的幫助

public class Stock { 

    Stock() { 
    } 

    Produit [] pdt ; 
    Fournisseur [] four; 
    int [] qte ; 
    int t = 0; 

    void enregistrer(Produit p , Fournisseur f , int q) { 
    pdt[t] = p ; 
    four[t] = f ; 
    qte[t] = q ; 
    t++ ; 
    } 

    void afficher() { 
    for (int i = 0 ; i < pdt.length ; i++) { 
     System.out.println("Le produit "+pdt[i].getNomP()+"à pour fournisseur : "+four[i].getNomEnt()+" et la quantité est de "+qte[i]); 
    } 
    } 
} 
+3

請正確縮進您的代碼。 – arshajii

回答

1

你必須初始化數組在構造函數:

Stock() { 
    pdt = new Produit[1024]; 
    four = new Fournisseur[1024]; 
    qte = new int[1024]; 
} 

1024只是陣列大小的一個例子。您應該實現數組的大小調整或綁定檢查。

0

看來你正在使用未初始化的變量。 這樣做:

Produit [] pdt ; 
Fournisseur [] four; 
int [] qte ; 
int t = 0; 

你沒有初始化的對象,你應該例如做:

Stock(int number) { 
    pdt=new Produit[number] 
    ... 
} 

這,往往會獲得在構造函數中,當你incentiate對象使用:

Stock stock=new Stock(100); //100 is the number of array objects 
0

您正在嘗試使用未分配的所有數組。所有這些都必須在構造函數中,如果你知道自己的最大尺寸來分配d(讓它MAX_SIZE):

Stock() { 
    Produit [] pdt = new Produit[MAX_SIZE]; 
    Fournisseur [] four = new Fournisseur[MAX_SIZE]; 
    int [] qte = new int[MAX_SIZE]; 
} 

否則,如果你不知道它的最大尺寸,或者如果你只是想節省內存你可以在每次調用它時在enregistrer()函數中重新分配它們:

void enregistrer(Produit p , Fournisseur f , int q) { 

    /* resize pdt array */ 
    Produit[] pdt_new = new Produit[t+1]; 
    System.arraycopy(pdt, 0, pdt_new, 0, t); 
    pdt_new[t] = p; 
    pdt = null; // not actually necessary, just tell GC to free it 
    pdf = pdt_new; 
    /********************/ 

    /* the same operation for four array */ 
    Fournisseur[] four_new = new Fournisseur[t+1]; 
    System.arraycopy(four, 0, four_new, 0, t); 
    four_new[t] = f; 
    four = null; 
    four = four_new; 
    /********************/  

    /* the same operation for qte array */ 
    int[] qte_new = new int[t+1]; 
    System.arraycopy(qte, 0, qte_new, 0, t); 
    qte_new[t] = q; 
    qte = null; 
    qte = qte_new; 
    /********************/ 

    t++ ; 
} 
相關問題