2011-04-24 61 views
1

代碼:將數據存儲到對象數組元素返回空指針異常

import java.io.*; 

class Customer 
{ 
    String name; 
    int ID; 
    int purchasequantity; 
    double purchaseprice; 


    Customer() 
    { 
     name = ""; 
     ID = 0; 
     purchasequantity = 0; 
     purchaseprice = 0.0; 
    } 


} 

class StoreSell 
{ 
    public static void main(String args[]) throws IOException 
    { 
     Customer[] cst = new Customer[3]; 

     InputStreamReader isr = new InputStreamReader(System.in); 
     BufferedReader br = new BufferedReader(isr); 

     double totalAmount = 0; 

     System.out.println("Size of Array " + cst.length); 

     for (int i=0;i<cst.length;i++) 
     { 
      System.out.println("Enter Customer Name : "); 
      cst[i].name = br.readLine(); 
      cst[i].ID = 100 + (i+1); 
      System.out.println("Customer ID Generated is : "+cst[i].ID); 
      System.out.println("Enter Purchase Price per Piece : "); 
      //String price = br.readLine(); 
      //System.out.println("Entered Price is " +price); 
      cst[i].purchaseprice = Double.parseDouble(br.readLine()); 
      System.out.println("Enter Purchase Quantity : "); 
      cst[i].purchasequantity = Integer.parseInt(br.readLine()); 
     } 

     System.out.println(" Customer ID " + "Customer Name " + "Price Per Piece " + "Quntity " + "Bill Amount "); 

     for(int i=0;i<cst.length;i++) 
     { 
      System.out.print(cst[i].ID + " " +cst[i].name+" "+ cst[i].purchaseprice + " " + cst[i].purchasequantity); 
      double tempAmount = StaticMethod.calculateStatic(cst[i].purchaseprice, cst[i].purchasequantity); 
      totalAmount = totalAmount + tempAmount; 
      System.out.println(" " + tempAmount); 
     } 

     System.out.println("Total Sell of the day : Amount : " + totalAmount); 
    } 

} 

輸出:

Size of Array 3 
Enter Customer Name : 
Nirav 
Exception in thread "main" java.lang.NullPointerException 
    at StoreSell.main(StoreSell.java:38) 

說明:

  1. 的所述節目d不會拋出任何編譯錯誤。
  2. 在運行程序時,如果在控制檯上爲Name輸入數據,它可以從控制檯獲取數據,但無法存儲到數組對象中。
  3. 我試圖將從控制檯檢索到的數據存儲到一個臨時變量(不是數組元素)中,並且它存儲正確。
  4. 因此,我可以斷定只有當它試圖將數據存儲到數組對象時纔會出現問題。
  5. 但是,數組已成功創建。我試圖打印數組的長度。它給出了正確的長度.. 3.

請幫我對此,我試圖谷歌很多,但無法找到任何相同的修復。

回答

4

初始化數組使用默認值填充數組中的所有位置,而對於對象數組,默認值爲null。所以下面的代碼:

Customer[] cst = new Customer[3]; 

創建以下數組:

{null, null, null} 

有初始化數組的多種方式,但如果你只肯定將要使用3元素數組只是去這一個:

Customer cst[] = {new Customer(), new Customer(), new Customer()}; 
+0

雅的工作..謝謝.. :) – 2011-04-24 11:21:49

8
Customer[] cst = new Customer[3]; 

這會創建數組,而不是單個元素,您需要自己創建這些元素,例如,在循環:

for (int i=0;i<cst.length;i++) 
{ 
    cst[i] = new Customer(); 
+0

是的..它的工作..謝謝... :) – 2011-04-24 11:22:12

+1

保持忘記,Java初始化數組與空對象= /。很好的接收。 – 2011-04-24 11:39:06

1

這是一個猜測* 叫我瘋但這樣做,CST [I] .ID = 100 +(I + 1);實際上增加我?

+0

是的..它不增加我,但它確實增加ID的值與增量在我。 – 2011-04-24 11:23:45