将数据存储到Object Array Elements中会返回NullPointerException

时间:2011-04-24 10:43:09

标签: java arrays nullpointerexception

代码:

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. 上述程序不会抛出任何编译错误。
  2. 在运行程序时,在控制台上为Name输入数据时,它可以从控制台获取数据,但无法存储到数组对象中。
  3. 我试图将从Console中检索到的数据存储到临时变量(非数组元素)中,并且存储正确。
  4. 因此,我可以得出结论,只有在尝试将数据存储到数组对象中时才会出现问题。
  5. 但是,数组已成功创建。我试图打印数组长度。它给出了正确的长度.. 3.
  6. 请帮我解决这个问题,我试过google很多,但是找不到相同的修复方法。

3 个答案:

答案 0 :(得分:8)

Customer[] cst = new Customer[3];

这会创建数组,而不是单个元素,您需要自己创建这些元素,例如:在循环中:

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

答案 1 :(得分:4)

初始化数组会使用默认值填充数组中的所有位置,对于对象数组,默认值为null。所以下面的代码:

Customer[] cst = new Customer[3];

创建以下数组:

{null, null, null}

有许多方法可以初始化数组,但是如果你肯定只使用3元素数组,那就去找一个:

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

答案 2 :(得分:1)

这是一个猜测* 叫我疯了但这样做,cst [i] .ID = 100 +(i + 1);实际上增加我?