Click here to Skip to main content
15,844,498 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to use the nextInt method of Random to select and return one item from the list. I need the method to return any of the strings in the list, regardless of the size of the list. However, the list will always have at least one item in it.

What I have tried:

Here is my method at the moment but it gives me errors that variable choices is already defined in this method and variables ArrayList and String are undeclared.

Java
<pre>/**

* Return a random one of the strings in the given list.

* The list will have at least one item in it.

* @param choices A list of strings.

* @return One of the strings in the given list.

*/

public String chooseOne(ArrayList<String> choices)

{

Random rand = new Random();

ArrayList<String>choices;

return rand.nextString(ArrayList<String>choices);
Posted
Updated 24-Nov-22 16:23pm

1 solution

Lets see if we can annotate this a bit:
Java
public String chooseOne(ArrayList<String> choices) {
    Random rand = new Random();
    // Up to this point, all is good.
    ArrayList<String> choices;  // Error: this attempts to define a new choices variable
    // but we already have a choices variable defined in the parameter list
    return rand.nextString(ArrayList<String> choices);
    // Error:  There is no nextString method for a rand object.
}

Given that ArrayList.size() returns the number of elements in the list and rand.NextInt(int bound) returns the next integer in the range (0 .. bound), you should be able to figure how to fix your code.
 
Share this answer
 
Comments
Freddie Francis 25-Nov-22 7:41am    
would this be correct.
Random rand = new Random();
int index = rand.nextInt(choices.size());
return choices.get(index)
k5054 25-Nov-22 9:59am    
Correct.
Or you could do it in one line
   return choices.get( rand.nextInt( choices.size() ) );

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900