Java Array索引超出范围异常修复

时间:2015-09-30 01:35:36

标签: java indexoutofboundsexception

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

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;
    }
}

2 个答案:

答案 0 :(得分:1)

基于......

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)];

答案 1 :(得分:1)

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

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)];