CS 145 Lab 8
Reminder
- Show your instructor or TA your already completed checkpoints from lab 7 in the first 20 minutes of this lab.
Arrays
As discussed in class and in your textbook, arrays are simply number collections of data. We can have arrays of primitives and we can have arrays of objects. Making an array looks similar to making an object, except we must specify how many items we’ll store and our types have the form typename[]:
int[] counts = new int[100];
String[] names = new String[3];
Accessing the array and assigning an element of the array require an integer subscript, but otherwise these operations look very similar to referencing and assigning a plain old variable:
counts[0] = counts[0] + 1;
names[2] = "Slar";
We often need to march through an array one element at a time, which looks very similar to marching through a String one character at a time (in fact, Strings are really just char arrays):
for (int i = 0; i < names.length; ++i) {
System.out.println(names[i]);
}
Swapping
Swapping values between variables or elements of an array is something we occasionally have to do. In assigning a value, we lose the old value, so we have to make a copy of the old value before we lose it. Here’s how we might swap two ints a and b:
int tmp = a;
a = b;
b = tmp;
Several of the problems below may benefit from swapping.
Problems
Complete three of the following problems:
- Rewrite the dice problem from the previous lab to use an array rather than six counters. (Your array must not contain wasted elements.)
- Suppose you have a list of 10 names as Strings. (Hardcoded is fine.) Write code to randomly pick and print 5 of them, without repeats.
- Suppose you have a String. (Hardcoded is fine.) Write code to count the frequency of each alphabetic letter. This problem is deftly solved if you can get the “serial number” of a letter, i.e., a = 0, b = 1, c = 2. Good news. Just subtract ‘a’ from your character and you’ll get that serial number. Character arithmetic is supported by Java. Print the frequencies after all characters have been processed.
- Write a method named join that takes an array of Strings as its argument. It returns a String of the form “value0,value1,value2,…” No credit will be given if you do not have a method with the prescribed structure.
- There are many algorithms for sorting data in an array. One simple one is called the selection sort. It can be described in pseudocode:
for each cell in the list find the smallest value in the sublist starting at the current cell swap that smallest value with the value in this cell
Translate this algorithm into Java and sort an array of ints.
TODO
- Work on preassignment 3.