代码:
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)
说明:
请帮我解决这个问题,我试过google很多,但是找不到相同的修复方法。
答案 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);实际上增加我?