mercredi 24 octobre 2018

Java method to return random element of array of different types

I would like to pass different arrays of changing parameter types at different times into a method/function of which randomly returns one element, however am extremely struggling to do so using Java.

I have attempted to do so using the following code:

public int rndInx(Array theArray) {
    theArray = theArray[(int)(Math.random() * theArray.length)];
    return theArray;

}

However, Eclipse draws attention to errors; length not being resolved and the type of expression must be an array type. I assume one cause of the issue is the returnType, however I'm unsure what type would accept a range of returnTypes. I am aware that the syntax is probably extremely wrong too since I've only recently began to learn Java :(

For example, if I was to pass an array containing integers, then one random integer element would be returned - and if I was to pass an array containing strings etc. than one random element from the array in question would be returned.

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire