tryAndroid
tryAndroid

Reputation: 95

Randomize from a made list

ArrayList<String> listArray = new ArrayList<String>();

private void AddToListActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String addTo = txtAdd.getText();
    listArray.add(addTo);
}                                        

private void randomPickerActionPerformed(java.awt.event.ActionEvent evt) {                                         

} 

In the button randomPicker, I want to print out one of the random strings I added in my array. Can you guys help me out with what I should write inside that button?

I tried:

   String random = (listArray[new Random().nextInt(listArray.length)]);
    System.out.println(random);

It said i couldn't use nextInt

Upvotes: 2

Views: 53

Answers (3)

Tatarize
Tatarize

Reputation: 10816

It depends a bit on what you want this stuff for. But, generally there's two things. You can use the class Random to pick a random index in your ArrayList.

Or you can use the collections java.util.Collections.shuffle() method.

public static void shuffle(List<?> list)

To shuffle the entire List.

Random random = new Random();
int index = random.nextInt(listArray.size());
String random = listArray.get(index);

My guess is you're coming from c++. The ArrayLists in java are backed by actual arrays. But, they are not accessible. You don't call .length on them, but .size()

Upvotes: 0

Shadov
Shadov

Reputation: 5591

String random = (listArray[new Random().nextInt(listArray.length)]);

You are using syntax for arrays, and your listArray is actually an ArrayList (you are doing somewhere else list.add() that's how I guess). You need to invoke a get method of the ArrayList, like this:

String random = listArray.get(new Random().nextInt(listArray.size()));

Notice the size() method, length property is just for arrays.

Upvotes: 1

Md Ayub Ali Sarker
Md Ayub Ali Sarker

Reputation: 11567

you can do like this

Random ran = new Random();
String random = (String) list.get(ran.nextInt(list.size()));
System.out.println("random :"+rdom);

Upvotes: 0

Related Questions