# University of Washington, CSE 142

## Lab 7: Array methods

Except where otherwise noted, the contents of this document are Copyright 2012 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges, Whitaker Brand and Hélène Martin

# Basic lab instructions

• Talk to your classmates for help. You can even work on the lab with a partner if you like.
• You may want to bring your textbook to future labs to look up syntax and examples.
• Stuck? Confused? Have a question? Ask a TA for help, or look at the book or past lecture slides.
• Complete as many problems as you can within the allotted time. You don't need to keep working on these exercises after you leave the lab.
• Feel free to complete problems in any order.
• Before you leave today, make sure to check in with one of the TAs in the lab to get credit for your work.

# Today's lab

Goals for today:

• pass arrays as parameters and returns from methods
• explore the idea of reference parameters
• use arrays for tallying
• recall file Scanner usage
• Where you see this icon, you can click it to check the problem in Practice-It!

# Exercise : Array declaration syntax

Which of the following choices is the correct syntax for printing an array of integers named `a` as a comma-separated list of values enclosed in brackets?

# `Arrays` class methods

Method name Description
`Arrays.binarySearch(array, value)` returns index of value in a sorted array (< 0 if not found)
`Arrays.copyOf(array, length)` returns a new copy of an array
`Arrays.equals(array1, array2)` returns true if the two arrays contain same elements
`Arrays.fill(array, value)` sets every element to the given value
`Arrays.sort(array)` arranges the elements into sorted order
`Arrays.toString(array)` returns a string for the array, such as "[10, 30, -25, 17]"

# Exercise : Array reference mystery

What values are stored in the array at the comment in `main`? Note that the `incrementAll` method returns `void`, but does take an `int[]` parameter.

```public class ArrayReference {
public static void main(String[] args) {
int[] nums = {2, 4, -1, 3};
incrementAll(nums);

// HERE!
}

public static void incrementAll(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i]++;
}
}
}
```
index 0 1 2 3
value 3 5 0 4

# Exercise : Array reference mystery

Solve another reference mystery problem on PracticeIt!

Discuss it with your neighbor before submitting the answer and make sure you agree with each other's solution. There will be a problem of this type on the final!

# Exercise : `swapAll`

Write a method named `swapAll` that accepts two arrays of integers as parameters and swaps their entire contents. You may assume that the arrays passed are not null and are the same length.

For example, if the following arrays are passed:

```int[] a1 = {11, 42, -5, 27, 0, 89};
int[] a2 = {10, 20, 30, 40, 50, 60};
swapAll(a1, a2);
```

After the call, the arrays should store the following elements:

```a1: {10, 20, 30, 40, 50, 60}
a2: {11, 42, -5, 27, 0, 89}
```

# Exercise : `copyRange`

Write a method named `copyRange` that takes as parameters two arrays `a1` and `a2`, two starting indexes `i1` and `i2`, and a length `l`, and copies the first `l` elements of `a1` starting at index `i1` into array `a2` starting at index `i2`.

For example, if the following arrays are declared:

```int[] a1 = {10, 20, 30, 40, 50, 60};
int[] a2 = {91, 92, 93, 94, 95, 96};
copyRange(a1, a2, 0, 2, 3);
```

After the preceding call, the contents of `a2` would be `{91, 92, 10, 20, 30, 96}`. You may assume that the parameters' values are valid, that the arrays are large enough to hold the data, and so on.

# Exercise : `append`

Write a method called `append` that accepts two integer arrays as parameters and that returns a new array that contains the result of appending the second array's values at the end of the first array.

You should solve this problem in Practice-It!

# Exercise : `longestSortedSequence`

Write a method called `longestSortedSequence` that accepts an array of integers as a parameter and that returns the length of the longest sorted (nondecreasing) sequence of integers in the array.

You should solve this problem in Practice-It!

# Exercise : countWords errors

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ``` ```// Counts the total lines and words in the given input scanner. public static void countWords(Scanner input) { Scanner input = new Scanner(new File("example.txt")); int lineCount = 0; int wordCount = 0; while (input.nextLine()) { String line = input.line(); // read one line lineCount++; while (line.next()) { // count tokens in line String word = line.hasNext; wordCount++; } } } ```

The above attempted solution to Practice-It problem "`countWords`" has 5 errors. Open Practice-It from the link above, copy/paste this code into it, and fix the errors. Complete the code so that it passes the test cases.

1. line 3: should not declare another `Scanner` for the file
2. line 7: `nextLine` should be `hasNextLine`
3. line 8: `line` should be `nextLine`
4. line 10: need a second line `Scanner` to read the tokens of each line
5. line 11: `hasNext` should be `next()`
6. line 14: need to add 3 `println` statements to print line/word stats

# Exercise - solution

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ``` ```// Counts the total lines and words in the given input scanner. public static void countWords(Scanner input) { Scanner input = new Scanner(new File("example.txt")); int lineCount = 0; int wordCount = 0; while (input.hasNextLine()) { String line = input.nextLine(); // read one line lineCount++; Scanner lineScan = new Scanner(line); while (lineScan.hasNext()) { // count tokens in line String word = line.next(); wordCount++; } } System.out.println("Total lines = " + lineCount); System.out.println("Total words = " + wordCount); System.out.printf("Average words per line = %.3f\n", (double) wordCount / lineCount); } ```

# Exercise : `coinFlip`

Write a method named `coinFlip` that accepts a `Scanner` for an input file of coin flips that are heads (H) or tails (T). Consider each line to be a separate set of coin flips and output the number and percentage of heads in that line. If it is more than 50%, print "You win!". Consider the following file:

```H T H H T
T t    t  T h  H
h
```

For the input above, your method should produce the following output:

```3 heads (60.0%)
You win!

You win!
```

# Exercise : `printDuplicates`

Write a method `printDuplicates` that accepts a `Scanner` for an input file. Examine each line for consecutive occurrences of the same token on the same line and print each duplicated token along how many times it appears consecutively. For example the file:

```hello how how are you you you you
I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge
one fish two fish red fish blue fish
bow  wow wow yippee yippee   yo yippee   yippee yay  yay yay
```

leads to the following console output:

```how*2 you*4
I*3 Jack's*2 smirking*5

wow*2 yippee*2 yippee*2 yay*3
```

# Exercise : `mostCommonNames`

Write a method `mostCommonNames` that accepts a `Scanner` for an input file with names on each line separated by spaces. Some names appear multiple times in a row. For example:

```Benson Eric   Eric  Marty Kim  Kim Kim   Jenny  Nancy Nancy  Nancy  Paul  Paul
Stuart Stuart Stuart Ethan Alyssa Alyssa Helene Jessica Jessica Jessica Jessica
Jared  Alisa Yuki   Catriona  Cody   Coral   Trent Kevin  Ben Stefanie Kenneth
```

For each line, print the most commonly occurring name. If there's a tie, use the first name that had that many occurrences.

```Most common: Kim
Most common: Jessica
Most common: Jared
```

Also return the total number of unique names in the whole file (e.g. 23 for the above input).

# Exercise : `stripHtmlTags`

Write a method `stripHtmlTags` that accepts a `Scanner` for an input file containing an HTML web page, then reads that file and prints the file's text with all HTML tags removed. A tag is any text between the character < and >. For example, consider the following text:

```<html>
<title>My web page</title>
</html>
```

If a file containing these lines were passed to your program, your program should output the following:

```

My web page

```

# Exercise : `wordLengths`

Write a method called `wordLengths` that accepts a Scanner representing an input file as its argument. Your method should read from the given file, count the number of letters in each token in the file, and output a result diagram of how many words contain each number of letters. Use tabs before the asterisks so that they'll line up. If there are no words of a given length, omit that line from the output.

You should solve this problem in Practice-It!

# If you finish them all...

If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.

You can view an exercise, type a solution, and submit it to see if you have solved it correctly.

Choose some problems from the book and try to solve them!