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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -