use*_*920 0 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
Run Code Online (Sandbox Code Playgroud)
我正在为一个编程类的项目工作,在尝试运行这个程序后,我在这里的代码中列出的四行上得到了NullPointerExceptions.我知道NullPointerException来自尝试访问null的东西,但我不确定如何解决它.
在无参数构造函数中删除此行.
generator = null;
Run Code Online (Sandbox Code Playgroud)
您正在"重置"先前初始化的Random实例,并导致NPE使用该实例在第一次尝试的方法调用上抛出:
初始化的替代方法Random generator可能是:
private final Random generator; // no init
public BlurbMaker() {
generator = new Random();
}
public BlurbMaker(Random iniGenerator) {
generator = iniGenerator;
}
Run Code Online (Sandbox Code Playgroud)
这将Random仅在需要时创建实例.
| 归档时间: |
|
| 查看次数: |
598 次 |
| 最近记录: |