-3

How can I print a string value from a list in java?

I have an array with more four strings. I want to print one of the value from the list randomly.

I tried this :

import java.util.Arrays;
import java.util.List;
import java.util.Random;

class Text {

    public static void main(String [] args) {

        String [] array = {"hello", "world", "coucou"};
        List <String> list = Arrays.asList(array);
        {
            System.out.println("String from the list ="+Random.array);
        }
    }
}

Can someone help resolve the syntax for System.out.println?

Thank you.

rageandqq
  • 2,221
  • 18
  • 24
kirk douglas
  • 577
  • 5
  • 18
  • 35
  • 2
    possible duplicate of [Retrieving a random item from ArrayList](http://stackoverflow.com/questions/5034370/retrieving-a-random-item-from-arraylist) – NESPowerGlove Feb 13 '15 at 20:18

3 Answers3

2

You can use the Random class to generate a random number between 0 (inclusive) and your list's length (exclusive), and print the value at that index.

Random rand = new Random();
System.out.println("String from list: " + list.get(rand.nextInt(list.size()));
rageandqq
  • 2,221
  • 18
  • 24
0

Before selecting the random element you can create a random number from range [0, n) where n is the size of the list.

You can use new Random(System.nanoTime()).nextInt(list.size()) to do it.

MateuszPrzybyla
  • 897
  • 8
  • 17
0
 public class ListExample {

    public static void main(String[] args) {



          String [] array = {"hello", "world", "coucou"};

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


         for(int i=0;i<array.length;i++){
             list.add(array[i]);
         }

        Random rnd=new Random();


        System.out.println("String from the list ="+list.get(rnd.nextInt(array.length)));

        }


}
SerefAltindal
  • 339
  • 3
  • 12