【发布时间】:2013-12-11 01:56:30
【问题描述】:
当我运行我的测试工具时,我得到一个 NullPointerException 就行了:
if(flower.extractPollen(pol)){
我很难解释。在我的测试工具中,我正在向我的花园实例添加鲜花,据我从 println 中可以看出,这些鲜花有花粉。在我的测试工具中,我正在创建一个花园实例,蜂王(在数组列表中)在蜂巢中,并将玫瑰和水仙花(在数组列表中)添加到花园中。然后我又在蜂巢和花园上跑了一天,又在花园里的花上跑了一天(向它们添加花粉,我可以看出这是从 println 发生的)并创造了更多的蜜蜂。当创建工蜂时,它应该从花园的实例中获取一朵花并从中提取花粉,但我得到的是 NullPointerException。相关代码:
public class Worker{
public Bee anotherDay(){
for(int u = 0; u< 2; u++){
Flower flower = Garden.getInstance().findFlower();
for(int pol = 5; pol>0; pol--){
if(flower.extractPollen(pol)){
if(pol>1){
hive.addRoyalJelly(1);
pol = pol - 2;
hive.addHoney(pol);
}
break;
}
}//code omitted which returns the bee in this method and some other methods from the class
}
}
public class Garden{
private ArrayList<Flower> flowerbed = new ArrayList<Flower>();
Hive hive = null;
private static Garden instance;
private Garden(){}
public static Garden getInstance(){
if(instance == null){
instance = new Garden();
}
return instance;
}
public void anotherDay(){
int size = flowerbed.size();
for(int i = 0; i < size; i++) {
Flower flower = flowerbed.get(i);
System.out.println(flower);
flower.grow();
}
}
public Flower getFlower(int fi){
if(fi < flowerbed.size()){
return flowerbed.get(fi);
}else{
return null;
}
}
public Integer getRandomInteger(Integer max)
{
Random rand = new Random();
int number;
number = rand.nextInt(max) + 1;
return new Integer(number);
}
public Flower findFlower(){
return getFlower(getRandomInteger(flowerbed.size()));
}
}
public abstract class Flower{
public boolean extractPollen(int po){
if(po <= pollen){
pollen= pollen - po;
return true;
}return false;
}
//subclasses are not abstract and in their grow methods pollen is added. Some other methods omitted
}
通过在我的代码周围使用 System.out.println() 我可以看到我使用的代码是在花园的实例中添加玫瑰和金莲花,并且在创建工蜂时(第 14 天) ) 它们分别有 28 和 42 种花粉。由于工人只是试图提取 5 我不明白为什么我会得到这个异常!堆栈跟踪:
Exception in thread "main" java.lang.NullPointerException
at Worker.anotherDay(Worker.java:21)
at Hive.anotherDay(Hive.java:105)
at TestBasicHive.testpart5(TestBasicHive.java:405)
at TestBasicHive.main(TestBasicHive.java:14)
【问题讨论】:
-
能否给我们看一下空指针异常的堆栈跟踪?
-
添加findFlower方法代码,即将添加stacktrace
-
rand.nextInt(max) + 1- 为什么是+ 1? -
@OliCharlesworth - 我以为我有这样做的理由,但是当我删除它时,它摆脱了空指针异常!谢谢-如果可以的话,我会将您的评论标记为正确的答案!
标签: java arraylist nullpointerexception singleton