2013-11-03 108 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++ ; 
} 
相关问题