我目前得到一個數組越界異常在執行線name.firstName = this.firstNames[rand.nextInt(NUM_NAMES)];
通常情況下我沒有發現這些異常,但是我一直停留在這一個一段時間以來的來源問題。任何幫助表示讚賞,類和堆棧跟蹤粘貼如下:Java數組索引越界異常修復
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;
}
}
也許'rand.nextInt(NUM_NAMES - 1)'? – MadProgrammer
沒有解決問題:( – GregH
我沒有看到任何地方,你叫'generateName'。考慮提供[可運行示例](https://stackoverflow.com/help/mcve),這說明您的問題。這不是一個代碼轉儲,但你在做什麼哪你凸顯遇到的問題的例子。這將導致更少的混亂和更好的反應 – MadProgrammer