当我运行方法runSnackBar时,我得到一个空指针异常错误,我无法解决原因。当我收到此错误时,BlueJ突出显示了randomFlavour方法中的第一行,但我不明白为什么。请帮忙。
import java.util.Random;
import java.util.ArrayList;
public class SnackBar
{
private Random randomGenerator;
private String[] packets;
private SnackMachine newSnackMachine;
private ArrayList<Student> students;
public SnackBar(int numOfStudents, int numPackOfCrisps, int cost)
{
randomGenerator = new Random();
String[] packets = {"ready salted", "cheese and onion", "salt and vinegar" , "smokey bacon"};
newSnackMachine = new SnackMachine(numPackOfCrisps , cost);
for(int n=0 ; n < numPackOfCrisps ; n++){
newSnackMachine.addPack(new PackOfCrisps(randomFlavour()));
}
students = new ArrayList<Student>();
for(int i=0 ; i < numOfStudents ; i++){
students.add(new Student(randomFlavour(), newSnackMachine));
}
}
private String randomFlavour()
{
int index = randomGenerator.nextInt(packets.length);
return packets[index];
}
public void describe(){
System.out.println("The SnackBar has" + students.size() + "hungry students");
System.out.println("The SnackMachine has:" + newSnackMachine.countPacks("ready salted") + "packets of ready salted crisps");
System.out.println("," + newSnackMachine.countPacks("cheese and onion") + "of cheese and onion crisps");
System.out.println("," + newSnackMachine.countPacks("salt and vinegar") + "of salt and vinegar crisps");
System.out.println("," + newSnackMachine.countPacks("smokey bacon") + "of smokey bacon crisps");
}
public void runSnackBar(int nSteps){
for( int x=1 ; x < nSteps ; x++){
System.out.println("Time step" + x);
describe();
int y = randomGenerator.nextInt(students.size());
students.get(y).snackTime();
}
}
}
答案 0 :(得分:3)
private String[] packets;
默认情况下, packets
是指定的null
,此处为
String[] packets = {"ready salted", "cheese and onion",
"salt and vinegar" , "smokey bacon"};
您声明本地变量。所以你在这里得到了NPE:
int index = randomGenerator.nextInt(packets.length);
↑
null
JLS 4.12.5. Initial Values of Variables:
对于所有引用类型(§4.3),默认值为null。
ArrayType是ReferejceType
答案 1 :(得分:1)
您试图在构造函数中初始化packets
,但是您意外地创建了一个局部变量。
更改
String[] packets = {"ready salted", "cheese and onion", "salt and vinegar" , "smokey bacon"};
到
packets = new String[] {"ready salted", "cheese and onion", "salt and vinegar" , "smokey bacon"};
所以packets
指的是你的实例变量,所以它会被正确初始化。