将数据存储到对象数组元素返回NullPointerException异常 [英] Storing data into Object Array Elements returns NullPointerException
本文介绍了将数据存储到对象数组元素返回NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
code:
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)
说明:
- 上述程序不抛出任何编译错误。
- 当运行程序,当控制台名称输入数据时,它能够从控制台读取数据,但无法存入数组对象。
- 我试图存储从控制台检索到一个临时变量(非数组)中的数据,并正确储存。
- 因此,我可以断定,只有当它试图将数据存储到一个数组对象出现问题。
- 然而,阵列创建成功。我试图打印数组的长度。并给出了正确的长度。3。
请帮我在这,我试图谷歌很多的钱,但没能找到相同的任何修补程序。
Please help me on this, I have tried to google lot on it, but not able to find any fix for the same.
推荐答案
正在初始化数组填充用默认值在阵列内所有的位置,并为对象的数组的默认值为null。所以下面code:
Initialising an array populates all positions within the array with the default value, and for an array of objects the default value is null. So the following code:
Customer[] cst = new Customer[3];
创建以下数组:
{null, null, null}
有初始化数组的多种方式,但如果你只肯定将要使用3元素数组只是去为这一个:
There are numerous ways of initialising arrays, but if you're definately only going to be using a 3 element array just go for this one:
Customer cst[] = {new Customer(), new Customer(), new Customer()};
这篇关于将数据存储到对象数组元素返回NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文