Hello DaniWeb,

Basically like the title suggests I am having trouble generating a random element from my array, and storing it in another array. I am quite new to Java, and the api is a little confusing but from what I can see there is no method for this. Searching online has returned this snippet of code

String[] fruits = { "apple", "apricot","orange", "pear", "plum", "peach",  "watermelon"};

String ret = pickRand.get(fruits);
System.out.println(ret);

although using the pickRand() function is throwing me up an error, even though I have imported java.until.Random.

Thank you for reading and any advice you throw my way.

- Static

Hey Static,

The way you declare a random is wrong. Here's how you do it.

First, declare that a variable is type Random and create a new Random object(this enables you to use methods of the Random Class)

Random pickRand = new Random();

Second, as far as I know, Random class can only generate actual values. (Boolean, double, float, int)

pickRand.nextInt(2); //0 or 1

The code above returns a value of type integer. the parameter (2) tells the generator to generate from values 0 OR 1.

Third, the way you refer to a fruit array is also wrong. It should be like this:

fruit[n] /*n is the index of the array that holds a value. In this case if n = 0 it will display apple.*/

Piece all the information I just told you and you should be able to display the array elements randomly.
Hint: Output fruit[n] where n is a random value/index. =]

He seems to be using this example code, which defines a "pickRand" class with a single method to get a random string from the array

class pickRand {
    public static String get (String[] array) {
        int rnd = generator.nextInt(array.length);
        return array[rnd];
    }
}

and he may have missed the part that says you have to create an instance of Random in your class

Random generator = new Random();

though there is no reason the author couldn't have just defined that 'generator' statically within his class.

There isn't even much reason to even make that a separate class for that - he could have just made it a method or in-lined the generator.nextInt() call with the array access.

StaticX,

Just to clarify (see Ezzaral's post), you are not just getting a random element from your fruits array. What happens is you are generating a random index within your array length

int rnd = generator.nextInt(array.length)

and then returning the element associated with that generated index

return array[rnd]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.