indexoutofboundsexception - Java Array index out of bounds exception fix -
i getting array out of bounds exception while executing line name.firstname = this.firstnames[rand.nextint(num_names)];
dont have issues finding source of these exceptions have been stuck on 1 time now. appreciated, class , stacktrace pasted below:
public class namegenerator { private static final int num_names = 200; private static final file names_file = new file("resources/info.dat"); /** random number generator */ private random rand; /** array of first names */ private string[] firstnames; /** 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 names 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 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 full name */ public static final class fullname { /** first name */ public string firstname; /** last name */ public string lastname; } }
based on...
try { readnamesfiles(); } catch (ioexception exp) { this.firstnames = new string[] { "john" }; this.lastnames = new string[] { "doe" }; }
there no guarantee arrays contain num_names
elements (you should logging exception @ least).
so using name.firstname = this.firstnames[rand.nextint(num_names)];
has potional cause serious issues, you've discovered.
instead, should work reality instead of assumptions, using more like...
name.firstname = this.firstnames[rand.nextint(this.firstnames.length)];
Comments
Post a Comment