如何解决这个NullPointerException?

时间:2013-03-14 15:24:58

标签: java nullpointerexception

package blurbProject;
import java.util.Random;
import java.util.Scanner;

public class BlurbMaker
{
Random generator = new Random(); //"Random" number generator for the Whatzits

public BlurbMaker()//constructor
{
    generator = null;
}//close constructor

public BlurbMaker(Random iniGenerator)//initialize constructor
{
    generator = iniGenerator;
}//close initialization

private String getWhoozitYs(){
    StringBuffer sb = new StringBuffer();
    boolean stop = generator.nextBoolean(); //NullPointerException here
    if(stop == true)
    {
        sb.append("y");
        getWhoozitYs();
    }
    return sb.toString();
}

private String getWhozit()
{
    StringBuffer sb = new StringBuffer();
    sb.append("x");
    sb.append(getWhoozitYs()); //NullPointerException here
    return sb.toString();
}

private String getWhatzit()
{
    StringBuffer sb = new StringBuffer();
    sb.append("q");
    boolean stop = generator.nextBoolean();
    if(stop == true)
    {
        sb.append("z");
    }
    else
    {
        sb.append("d");
    }
    sb.append(getWhozit()); //NullPointerException here
    return sb.toString();
}

private String getMultipleWhatzits()
{
    StringBuffer sb = new StringBuffer();
    sb.append(getWhatzit());
    boolean stop = generator.nextBoolean();
    if(stop == true)
    {
        sb.append(getWhatzit());
    }
    else
    {
        sb.append("");
    }
    return sb.toString();
}

public String generateBlurb()
{
    StringBuffer sb = new StringBuffer();
    sb.append(getWhozit());
    sb.append(getMultipleWhatzits());

    return sb.toString();
}

public static void main(String[] args)
{
    BlurbMaker blurbmaker = new BlurbMaker();

    Scanner scanner = new Scanner(System.in);
    System.out.print("How many blurbs would you like? ");

    int blurbNumber = scanner.nextInt();

    if(blurbNumber > 0)
        for(int i = 0; i < blurbNumber; i++){
            System.out.println("Blurb: " + blurbmaker.generateBlurb());
                            //NullPointerException on line above
        }
    else
        System.out.println("My work here is done.");

    scanner.close();
}//close main

}//close class

我正在为一个编程类的项目工作,在尝试运行这个程序之后,我在这里的代码中列出的四行上得到了NullPointerExceptions。我知道NullPointerException来自于尝试访问null的东西,但我不确定如何解决它。

2 个答案:

答案 0 :(得分:8)

在无参数构造函数中删除此行。

generator = null;

您正在“重置”以前初始化的Random实例并导致在使用该实例的第一次尝试方法调用时抛出NPE

初始化Random generator的替代方法可能是:

private final Random generator; // no init

public BlurbMaker() {
   generator = new Random();
}

public BlurbMaker(Random iniGenerator) {
   generator = iniGenerator;
}

只有在需要时才会创建Random的实例。

答案 1 :(得分:2)

将无参数构造函数调用到BlurbMaker(),将生成器初始化为null。然后在生成器上调用一个方法,该方法为null。因此NPE。