gpt4 book ai didi

java - 如何修复这个 NullPointerException?

转载 作者:行者123 更新时间:2023-12-01 06:45:37 26 4
gpt4 key购买 nike

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

我正在为一个编程类(class)开发一个项目,在尝试运行该程序后,我在此处的代码中列出的四行上遇到了 NullPointerExceptions。我知道 NullPointerException 来自尝试访问 null 的内容,但我不确定如何修复它。

最佳答案

删除无参构造函数中的这一行。

generator = null;

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

初始化随机生成器的替代方法可能是:

private final Random generator; // no init

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

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

仅在需要时才会创建 Random 实例。

关于java - 如何修复这个 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15413354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com