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)
JavaScript
x
21
21
1
String n001 = "I";
2
String n002 = "look";
3
String n003 = "and";
4
String n004 = "stare";
5
String n005 = "so";
6
7
Random bob = new Random();
8
9
String num_1 = String.format("%03d", bob.nextInt(298));
10
System.out.println(num_1);
11
String num_2 = String.format("%03d", bob.nextInt(298));
12
System.out.println(num_2);
13
String num_3 = String.format("%03d", bob.nextInt(298));
14
System.out.println(num_3);
15
String num_4 = String.format("%03d", bob.nextInt(298));
16
System.out.println(num_4);
17
String num_5 = String.format("%03d", bob.nextInt(298));
18
System.out.println(num_5);
19
20
String num1 = "n" + num_1;
21
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.