jeudi 2 juillet 2015

Get a random text from ArrayList

I'm just learning Java and I'm having a problem with ArrayList or retrieving a random line of text. What I'm trying to achieve is a random quote (from a list) to load on every page refresh. Never done an Array/Random before, not sure if this is the right method?

Here's what's working so far: http://ift.tt/1en0BXR

code that's not working:

 Random random = new Random(); 
 int index = random.nextInt(10);


    List<String> list = new ArrayList<String>();
    list.add("quote1");
    list.add("quote2");
    list.add("quote3");
    list.add("quote4");
    list.add("quote5");

    RandomExample obj = new RandomExample();
    for(int i = 0; i < 10; i++){
        System.out.println(obj.getRandomList(list));
    }

}

getRandomList(List<String> list) {

    //0-4
    int index = random.nextInt(list.size());
    System.out.println("\nIndex :" + index );
    return list.get(index);

}




Aucun commentaire:

Enregistrer un commentaire