Lecture 15 (Sherriff) - Arrays

Lecture Date: Monday, February 16

The first files we read in class on Friday just had one piece of data per line. Those were easy to deal with!

When we look at the data from wendys.csv, misspellings.csv, names.csv, and Lou’s List, we see that each line that we want to read from the file has multiple pieces of data. This is actually much more common. Think of each line as a line in a spreadsheet.

What we need is a way to represent an entire line, with the ability to get each individual piece of data.

Another thing that would be helpful is in a situation where we wanted to record, say, phone numbers or email addresses. Most people have more than one phone number or email address they can be reached at nowadays. It’s super inefficient to do:

Bad Way To Store Lots of Data!
String emailAddress1 = "sherriff@virginia.edu";
String emailAddress2 = "mss2x@virginia.edu";
String emailAddress3 = "profsherriff@gmail.com";

What if you had 5 email addresses? What happens to the other two? What about if you only had one email address? Would you leave the others blank? There has to be a better way!

And there is! Arrays!

Array of Email Addresses
String[] emailAddresses = new String[3];
emailAddress[0]= "sherriff@virginia.edu";
emailAddress[1]= "mss2x@virginia.edu";
emailAddress[2]= "profsherriff@gmail.com";

Why is this better? Well if we want to loop though all the emails…

Looping through array
for(int i = 0; i < emailAddresses.length; i++) {

Using an array allows you to store all like data together in effectively one location… one location that can have multiple variables with it!

Let’s create some arrays and then do some simple math:

  • What’s the average of the numbers in the array?
  • What’s the largest value in the array?
  • What’s the smallest value in the array?
  • How many 7’s are in the array?

Example Code: