[英]Java Array index out of bounds exception fix
我目前在执行行name.firstName = this.firstNames[rand.nextInt(NUM_NAMES)];
时得到一个数组越界异常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;
}
}
基于...
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)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.