gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:42:17 24 4
gpt4 key购买 nike

代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com