Search code examples
javarandomarraylist

how do i change this to be able to generate a random item from my list?


my list containing fruits

i'd like for the code to pick (At random) a fruit from my list and then display it.

the code works currently but doesn't have the random function i'd like for it to have. This is a school project so any help is appreciated


Solution

  • You need to obtain random integer number and then use it as an index to get from list.

    Try this sample:

    int randomIndex = rand.nextInt(0, list.size());
    System.out.println(list.get(randomIndex));
    

    instead of your "for" cycle

    Some explanation for newcomer: nextInt method will return some random integer number from 0 (index cannot be less then 0) to list.size() number exclusively (counting starts with 0, so if you have 3 elements, the third element will be at index 2) to prevent IndexOutOfBoundException.