how to get a random value from one array to another in java -


i want random array value char[] vowel , char[] consonant char[] firstname , char[] lastname.

my ide (eclipse) shows no errors

firstname[i]=consonant [random.nextint(consonant.length)];

however when running code i'll error

`exception in thread "main" java.lang.arrayindexoutofboundsexception: 0     @ _01namegenerator.main(_01namegenerator.java:27)` 

how shall fix statement?

// http://www.javapractices.com/topic/topicaction.do?id=62 import java.util.random;  public class _001namegenerator {      public static void main(string[] args) {         random random = new random();          int firstnamelength = 7; // fixed length, not "random"         int lastnamelength = 5;            system.out.println("your firstname "+firstnamelength+" , lastname "+lastnamelength+" characters long.");          char[] vowel = {'a', 'e', 'i', 'o', 'u', 'y'};               char[] consonant = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z'};          char[] firstname = new char[firstnamelength];         char[] lastname = new char[lastnamelength];           boolean wechsel = true;          (int = 0; < firstnamelength; i++) {              if (wechsel == true){                  firstname[i]=consonant [random.nextint(20)];  // length of consonant array                 wechsel = false;              } else {                  firstname[i]=vowel [random.nextint(6)]; // length of vowel array                 wechsel = true;             }          }             (int = 0; < lastnamelength; i++) {              if (wechsel == true){                  lastname[i]=consonant [random.nextint(20)];                 wechsel = false;              } else {                  lastname[i]=vowel [random.nextint(6)];                 wechsel = true;             }          }             system.out.println(firstname + "\n" + lastname);      }  } 

char[] firstname = {}; char[] lastname = {}; 

these 2 lines generate empty lists, whenever try add gives arrayindexoutofboundsexception: 0.

since have random length above, try instead:

char[] firstname = new char[firstnamelength]; char[] lastname = new char[lastnamelength]; 

also, in case wouldn't have known length of arrays beforehand, can use arraylist, created these kind of purposes.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -