我正在进行模拟,每次都会出错! 我试过evreything但我找不到答案。 这是代码: Person.java:
package School;
import java.util.Random;
public class Person {
private Random rng;
private String Name;
private String[] Friends;
private int Hobby;
private boolean IsDitch;
public Person(String Name, String[] Friends, int Hobby, boolean IsDitch){
int aof = rng.nextInt(20);
this.Name = Name;
this.Friends = Friends;
Friends = new String[aof];
this.Hobby = Hobby;
if(rng.nextInt(10) == 0){
IsDitch = true;
}else{
IsDitch = false;
}
this.IsDitch = IsDitch;
}
public boolean getIsDitch(){
return IsDitch;
}
public int getMaxFriends(){
return Friends.length;
}
public String getName(){
return Name;
}
}
Interaction.java:
package School;
public class Interaction {
public static void main(String[] args){
String[] g;
g = new String[2];
g[0] = "Natasha";
g[1] = "Fill";
Person mrt = new Person("Adam",g,2,false);
System.out.println(mrt.getName());
}
}
我得到的错误:
Exception in thread "main" java.lang.NullPointerException
at School.Person.<init>(Person.java:12)
at School.Interaction.main(Interaction.java:9)
答案 0 :(得分:1)
rng
是null
,您在实例化它之前在构造函数中使用它。
将其更改为:
rng = new Random();
int aof = rng.nextInt(20);
您甚至可能希望rng
静态,具体取决于您的确切需求。
答案 1 :(得分:-1)
我认为这是因为你没有初始化rng
编辑:oops太慢,但我同意peter.petrov