CS 145 Lab 7 – Arrays and ArrayLists
First, if you have checkpoints left over from last lab, get them inspected during the first 15 minutes of this lab. No credit will be awarded past these 15 minutes.
Don’t forget to work in pairs! Where possible, please work with someone that you did not work with last lab. The exchange of new ideas and perspectives is not an opportunity you want to rob yourself of.
Objective
In this lab you will learn about storing and processing collections of data in arrays and ArrayList
s. Arrays let us number our data, making it easy to loop through the collection or associate data with the natural numbers. However, arrays are not flexible in structure. Before we can use them, we must know how many elements we’ll need. Adding and removing elements are not builtin operations. ArrayList
is a class that wraps around an array and offers methods for adding, removing, locating, and many other operations.
Checkpoints 1 and 2
Solve two of the following problems:
- You are given a list of items. For example, to make a cinnamon-sugar blend, your list of items is [cinnamon, sugar]. You are also given a list of integer parts, describing how much of each item should be mixed together. For example, the scientifically-proven best cinnamon-sugar blend is 1 part cinnamon, 3 parts sugar. Thinking in parts is somewhat awkward; you’d prefer to think in percentages. Let’s write code to convert a parts list into a percentages list:
- Write a method
getItemsAndParts
that accepts anArrayList<String>
and anArrayList<Integer>
as parameters. It prompts the user to enter items and their integer parts, storing them in the parameter lists. - Write a method
sum
that accepts anArrayList<Integer>
and returns the sum of all the integers in the list. For example, if the parts list is [1, 3], the sum is 4. - Write a method
toPercentages
that accepts anArrayList<Integer>
of parts and returns anArrayList<Double>
of the percentages corresponding to the parts. For example, if the parts last was [1, 3], the the percentages list is [0.25, 0.75].
- Write a method
- You are running an election that combines the best principles of popular vote and fate, as determined by
Random
. You are given a list of names and a parallel list of counts, wherecounts[i]
represents the number of votesnames[i]
received. You’d like to create a new list in whichnames[i]
appearscounts[i]
times, but with all the names mixed together in a random order. Write a method that accepts the two lists as parameters, generates a randomly sorted list with the names weighted by popular vote, and returns as winner the name at element 0 in the random list. You can randomize the list withCollections.shuffle(list)
. - You have a list of words. You have another list of stop words, words that you’d like to remove from the first list. Write a method that accepts these two lists and returns a new list containing only the words of the first list that are not stop words.