0

I'm trying to randomly select elements from 3 array of Strings?

private static String[] one   ={"dog, cat"};
private static String[] two   ={"ate, ran"};
private static String[] three ={"away, some}"

Random words = new Random();
int index=words.nextInt(one.length+two.length+three.length);

System.out.println(one[index]);
  • 2
    What do you think `words.nextInt(one.length+two.length+three.length);` does or should do and why do you think so? – Pshemo Dec 15 '15 at 03:25
  • Are you trying to pick one random element from any of the three arrays or one random element from each of the three arrays? – Daniel Centore Dec 15 '15 at 03:55

2 Answers2

1

The problem with the program is that you're getting a random number between 0 and 6 and then using this random number as an index to get a value from only the first array. There are two problems here,

  1. one[index] will cause an arrayindexoutofboundsexception in some cases because the max index for one is 1 when index can also be 2,3,4, or 5.

  2. also, the objective is to get a random element from THREE arrays of strings, not just one

My suggestion is getting a random number between one and three (inclusive) to choose one of the string arrays, then find a random number between 0 and the chosen array's length. And assign that to the index of the chosen array.

Chris Gong
  • 8,031
  • 4
  • 30
  • 51
0

A two step approach is probably best:

  1. Combine all your arrays into one larger array. This SO thread demonstrates several ways to accomplish this. For example, try this method (from here):

    public String[] concat(String[] a, String[] b) {
        int aLen = a.length;
        int bLen = b.length;
        String[] c= new String[aLen + bLen];
        System.arraycopy(a, 0, c, 0, aLen);
        System.arraycopy(b, 0, c, aLen, bLen);
        return c;
    }
    
    // use it like this
    String[] combined = concat(concat(one, two), three);
    
  2. Pick a random element from the combined array, and print it:

    int index = r.nextInt(combined.length);
    System.out.println(combined[index]);
    
Community
  • 1
  • 1
jfdoming
  • 975
  • 10
  • 25