为什么会出现NullPointerException& ArrayIndexOutOfBoundsException错误

时间:2014-12-11 09:02:11

标签: java arraylist nullpointerexception

在主要方法的第24行(第二个用于循环)和NullPointerError上获得arrayoutofindexexception。我不知道如何解决这个问题,我将非常感谢您的解释。请帮忙!

编辑:' NullPointerError'解决了,只需要为它初始化ArrayList,但仍然无法解决' ArrayOutOfIndexException'错误。

import java.util.*;

public class SnackBar
{
    private Random randomizer;
    private String[] flavours;
    private SnackMachine barMachine;
    ArrayList<Student> students;

    public SnackBar(int numStudents, int packetsBarMachine, int costPacket)
    {
        randomizer = new Random();
        flavours = new String[] {"prawn cocktail", "tango cheese", "natural", "paprika", "salt and vinegar"};
        barMachine = new SnackMachine(packetsBarMachine, costPacket);
 students = new ArrayList<Student>();

        for(int i = 0; i < packetsBarMachine; i++)
        {
            barMachine.addPack(new PackOfCrisps(randomFlavour()));
            i++;
        }

        for(int j = 0; j < numStudents; j++)
        {
            students.add(new Student(randomFlavour(), barMachine));            
            j++;
        }
    }

    public String randomFlavour()
    {
        int random = randomizer.nextInt(flavours.length);
        return flavours[random];
    }

    public void describe()
    {
        System.out.println("The SnackBar has " + students.size() + " hungry students.");
        System.out.println("The Snackmachine has:");
        System.out.println(barMachine.countPacks("prawn cocktail") + " packets of prawn cocktail crisps,");
        System.out.println(barMachine.countPacks("tango cheese") + " packets of tango cheese crisps,");
        System.out.println(barMachine.countPacks("natural") + " packets of natural crisps,");
        System.out.println(barMachine.countPacks("paprika") + " packets of paprika crisps,");
        System.out.println(barMachine.countPacks("salt and vinegar") + " packets of salt and vinegar crisps.");
    }

    public void runSnackBar(int nSteps)
    {
        int step = 1;

        while(step <= nSteps)
        {
            System.out.println("Time Step " + step);
            describe();
            int atRandom = randomizer.nextInt(students.size());
            students.get(atRandom).snackTime();
            step++;
        }
    }

    public static void main(String[] args)
    {
        SnackBar bar = new SnackBar (Integer.parseInt(args[4]), Integer.parseInt(args[20]), Integer.parseInt(args[5]));

        bar.runSnackBar(Integer.parseInt(args[30]));
    }
}

1 个答案:

答案 0 :(得分:0)

首先,您应该初始化ArrayList<Student> students列表。

Integer.parseInt(args[30])也是可疑的,因为为了不抛出异常,你必须提供31个命令行参数。对于所有其他尝试访问args数组的元素而不首先检查其长度的情况也是如此。