samedi 12 octobre 2019

Selecting and displaying a random item from a list in Java

I am writing code that creates a list of friendly insults, and then randomly selects one to display. I have figured out the creating the list part but am struggling with randomly selecting an item to and outputting it. Below is the code I have so far. I have read here and elsewhere the possible code to begin the portion of selecting the random item but not how to output it.

I have dug around on this site as well as on other programming sites to try to find the correct way to randomly access the list. And I believe I have found that. What I have not been able to find is how to then output the random item from the list.

List<String> insults = new ArrayList<String>();

insults.add("You clinking, clanking, clattering collection of caliginous junk! \n");
insults.add("I'll explain and I'll use small words so that you'll be sure to understand, you warthog-faced buffoon. \n");
insults.add("I fart in your general direction. Your mother was a hamster and your father smelt of elderberries. \n");
insults.add("You are a sad strange little man, and you have my pity. \n");
insults.add("You are about one bit short of a byte. \n");

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

This code does not output so far. That's the only step i'm missing. Outputting at random one item from the list. Thanks in advance for the help.




Aucun commentaire:

Enregistrer un commentaire