java - 将数据存储到对象数组元素中返回 NullPointerException

标签 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. 在运行程序时,当在控制台输入名称的数据时,它能够从控制台获取数据,但不能存储到数组对象中。
  3. 我尝试将从控制台检索到的数据存储到一个临时变量(不是数组元素)中,并且存储正确。
  4. 因此,我可以断定只有当它试图将数据存储到数组对象时才会出现问题。
  5. 但是,数组创建成功。我试图打印数组长度。它给出了正确的长度.. 3.

请帮我解决这个问题,我已经尝试在谷歌上搜索了很多,但找不到任何修复方法。

最佳答案

Customer[] cst = new Customer[3];

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

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

关于java - 将数据存储到对象数组元素中返回 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5770093/

相关文章:

arrays - 将一维数组写入单列时出现错误

java - Java HashSet.isEmpty() 中的 NPE

java - 什么是NullPointerException,我该如何解决?

java - 如何从 TextView 中获取文本并将其格式化为美元货币?

java - 如何使用 Mockito 对返回的模拟对象进行断言

java - 如何将Spring框架和MySQL与Java swing应用程序结合起来?

arrays - Swift HTTP POST 二维数组

c++ 传递函数作为数组索引不起作用。

jsf - 尝试在构造函数中访问 @Inject bean 时出现 NullPointerException

java - 如何以编程方式编辑 TextView 参数?