I’m trying to try something out for my AP statistics class where I need to randomly select five words from the lyrics of a song and calculate the average length of those strings. This is what I have so far: (There’s 297 lyrics but I don’t want to type all of those out if it won’t work)
String n001 = "I"; String n002 = "look"; String n003 = "and"; String n004 = "stare"; String n005 = "so"; Random bob = new Random(); String num_1 = String.format("%03d", bob.nextInt(298)); System.out.println(num_1); String num_2 = String.format("%03d", bob.nextInt(298)); System.out.println(num_2); String num_3 = String.format("%03d", bob.nextInt(298)); System.out.println(num_3); String num_4 = String.format("%03d", bob.nextInt(298)); System.out.println(num_4); String num_5 = String.format("%03d", bob.nextInt(298)); System.out.println(num_5); String num1 = "n" + num_1;
What I can’t figure out is how to take the value in num1 to select one of the Strings named the same thing. I need to do that for all five selected random numbers.
I’m sure there’s a way to do this, but it’s my first year in a CS class and I can’t seem to find the answer anywhere.
Advertisement
Answer
Here is a suggestion.
- put all the words in a List<String>
(e.g.List<String> = new ArrayList<>()
) - Use
Collections.shuffle
to shuffle the list. - then take the first 5 entries.
Doing the above will guarantee you won’t repeat any word unless there are duplicates in the list.
Figuring out how to average the lengths is up to you.