[英]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.