Java 数组索引越界异常修复

Java Array index out of bounds exception fix

我目前在执行 name.firstName = this.firstNames[rand.nextInt(NUM_NAMES)]; 行时遇到数组越界异常 通常我在查找这些异常的来源时没有问题,但是我已经在这个问题上停留了一段时间了。感谢任何帮助,class 和堆栈跟踪粘贴在下面:

public class NameGenerator {
    private static final int NUM_NAMES = 200;
    private static final File NAMES_FILE = new File("resources/info.dat");

    /** a random number generator */
    private Random rand;

    /** the array of first names */
    private String[] firstNames;
    /** the array of last names */
    private String[] lastNames;

    /**
     * Default Constructor
     */
    public NameGen() {
        super();
        this.rand = new Random();

        try {
            readFile();
        } catch (IOException exp) {
            this.first = new String[] { "foo" };
            this.last = new String[] { "bar" };
        }
    }

    /**
     * Read the names from the file
     */
    private void readNFiles() throws IOException {
        List<String> tempFirst = new ArrayList<String>();
        List<String> tempLast = new ArrayList<String>();

        Scanner scnr = new Scanner(NAMES_FILE);

        while (scnr.hasNext()) {
            tempFirst.add(scnr.next());
            tempLast.add(scnr.next());
        }

        scnr.close();

        int size = tempFirst.size();

        this.first = new String[size];
        tempFirst.toArray(this.firstNames);

        this.last = new String[size];
        tempLast.toArray(this.last);
    }

    /**
     * @return a generated name
     */
    public FullName generateName() {
        FullName name = new FullName();
        name.first = this.firstNames[rand.nextInt()];

        name.last = this.lastNames[rand.nextInt()];
        return name;
    }

    /**
     * Class describing a full name
     */
    public static final class FullName {
        /** the first name */
        public String firstName;
        /** the last name */
        public String lastName;
    }
}

基于...

try {

    readNamesFiles();

} catch (IOException exp) {

    this.firstNames = new String[] { "John" };
    this.lastNames = new String[] { "Doe" };

}

不能保证您的数组将包含 NUM_NAMES 个元素(您至少应该记录异常)。

所以使用 name.firstName = this.firstNames[rand.nextInt(NUM_NAMES)]; 之类的东西可能会导致一些严重的问题,正如您所发现的那样。

相反,您应该使用现实而不是假设,使用更像...

name.firstName = this.firstNames[rand.nextInt(this.firstNames.length)];

以下是有问题的代码的摘要:

List<String> tempFirstNames = new ArrayList<String>(NUM_NAMES);
int size = tempFirstNames.size();

this.firstNames = new String[size];
FullName name = new FullName();
name.firstName = this.firstNames[rand.nextInt(NUM_NAMES)];

您正在使用 rand.nextInt(NUM_NAMES) 作为 firstNames 的数组索引。这将生成一个介于 0 和 NUM_NAMES 之间的数字。问题是无法保证数组 firstNames 的大小为 NUM_NAMES。正如@AngryProgrammer 指出的那样,您可以改用它:

name.firstName = this.firstNames[rand.nextInt(firstNames.length)];