所有这些类都编译得很好,但是当我尝试运行我的测试器类时,它会返回以下错误:
显示java.lang.NullPointerException:
空
显示java.lang.NullPointerException
在Bin.add(Bin.java:23)
在BinTest.main(BinTest.java:11)
以下是课程:
public class BinItem
{
private String mySKU;
private int myQuantity;
public BinItem( String sku, int quantity )
{
mySKU = sku;
myQuantity = quantity;
}
public String getSKU()
{
return mySKU;
}
public int getQuantity()
{
return myQuantity;
}
public String toString()
{
// Write code here to return a string using
// the format: “SKU <sku>: <quantity>”. For
// example: “SKU 12345-15: 4320”.
return "SKU <" + getSKU() + ">: <" + getQuantity() + ">";
}
}
import java.util.*;
public class Bin
{
private String myName;
private ArrayList<BinItem> myContents;
public Bin( String name )
{
myName = name;
}
public String getName()
{
return myName;
}
public ArrayList<BinItem> getContents()
{
return myContents;
}
public void add( BinItem b )
{
myContents.add(b);
}
public String toString()
{
String s = "Bin " + myName + ":\n";
for ( BinItem b : myContents )
{
s += b + "\n";
}
return s;
}
}
import java.util.*;
public class BinTest
{
public static void main( String[] args )
{
ArrayList<Bin> warehouse = new ArrayList<Bin>();
Bin a = new Bin("A");
Bin b = new Bin("B");
warehouse.add( a );
warehouse.add( b );
a.add( new BinItem("1234-0", 500 ) );
a.add( new BinItem("1234-1", 25 ) );
a.add( new BinItem("1234-2", 7720 ) );
b.add( new BinItem("1234-3", 1000 ) );
for ( Bin bn : warehouse )
{
System.out.println( bn );
}
}
}
答案 0 :(得分:5)
您尚未初始化myContents
ArrayList。你必须在使用它之前初始化它
private ArrayList<BinItem> myContents = new ArrayList<BinItem>();
答案 1 :(得分:1)
你从未初步化我的内心。使用此
public Bin( String name )
{
myContents = new ArrayList<BinItem>();
myName = name;
}