# University of Washington, CSE 142

## Lab 9: Final Exam Practice

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

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

# Basic lab instructions

• Mouse over if you're not sure what they mean!
• Talk to your classmates for help.
• 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 much of the lab as you can within the allotted time. You don't need to keep working on these exercises after you leave.
• Feel free to complete problems in any order.
• Make sure you've signed in on the sign-in sheet before you leave!

# Today's lab

Goals for today:

• Practice for the final exam. The lab today contains a third sample final that has the same structure as your upcoming final except for the Critter problem.
• Where you see this icon, you can click it to check the problem in Practice-It!

# Exercise : reference mystery

What four lines of output are produced by the following program?

```public class ReferenceMystery {
public static void main(String[] args) {
int y = 1;
int x = 3;
int[] a = new int[4];
mystery(a, y, x);                                             // 2 3 [0, 0, 17, 0][^0-9,]+
System.out.println(x + " " + y + " " + Arrays.toString(a));   // 3 1 [0, 0, 17, 0][^0-9,]+
x = y - 1;
mystery(a, y, x);                                             // 1 0 [17, 0, 17, 0][^0-9,]+
System.out.println(x + " " + y + " " + Arrays.toString(a));   // 0 1 [17, 0, 17, 0][^0-9,]+
}

public static void mystery(int[] a, int x, int y) {
if (x < y) {
x++;
a[x] = 17;
} else {
a[y] = 17;
}
System.out.println(x + " " + y + " " + Arrays.toString(a));
}
}
```

# Exercise : array simulation

Consider the following method:
```public static void mystery(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = i * array[i];
}
}
```

Indicate in the right-hand column what values would be stored in the int[] array after `mystery()` executes with the int[] array in the left-hand column passed in as a parameter.

 `{}` `{}` `{7}` `{0}` `{3, 2}` `{0, 2}` `{5, 4, 3}` `{0, 4, 6}` `{2, 4, 6, 8}` `{0, 4, 12, 24}`

# Exercise : inheritance mystery

Assume the following classes have been defined:

 ```public class A extends B { public void method2() { System.out.println("a 2"); } } ``` ```public class D extends B { public void method1() { System.out.println("d 1"); } } ``` ```public class C { public String toString() { return "c"; } public void method1() { System.out.println("c 1"); } public void method2() { System.out.println("c 2"); } } ``` ```public class B extends C { public String toString() { return "b"; } public void method2() { System.out.println("b 2"); } } ```

continued on the next slide...

# Exercise - inheritance mystery

 `b` `c 1` `a 2` `b` `c 1` `b 2` `c` `c 1` `c 2` `b` `d 1` `b 2`

Consider the code below that uses these classes.
Write each line of its output in the boxes at right.

```C[] elements = {new A(),
new B(),
new C(),
new D()};
for (int i = 0; i < elements.length; i++) {
System.out.println(elements[i]);
elements[i].method1();
elements[i].method2();
}
```

# Exercise : `printStrings`

Write a method called `printStrings` that takes as a parameter a `Scanner` holding a sequence of integer/string pairs and that prints to `System.out` one line of output for each pair with the given string repeated the given number of times.

You should solve this problem in Practice-It!

# Exercise : `reverseLines`

Write a method called `reverseLines` that takes a `Scanner` containing an input file as a parameter and that echoes the input file to `System.out` with each line of text reversed.

Example input Example output
```If this method works properly,
the lines of text in this file
will be reversed.

Remember that some lines might be blank.```
```,ylreporp skrow dohtem siht fI
elif siht ni txet fo senil eht
.desrever eb lliw

.knalb eb thgim senil emos taht rebmemeR```
Hint: check out lab 6 to review using `Scanners` over `Files` effectively. Check out lab 5 to review `String` processing.

# Exercise : `isAllEven`

Write a method called `isAllEven` that takes an array of integers as a parameter and that returns whether or not all of the values are even numbers (`true` for yes, `false` for no).

Input
Output
{18, 0, 4, 204, 8, 4, 2, 18, 206, 1492, 42} `true`
{2, 4, 6, 8, 10, 208, 16, 7, 92, 14} `false`

Hint: check out lab 7 to review how to deal with arrays!
Another hint: When can we safely say that every number is even? When can we safely say that not every number is even?

# Exercise : `removeShorterStrings`

Write a method called `removeShorterStrings` that takes an `ArrayList` of strings as a parameter and that removes from each successive pair of values the shorter string in the pair. If there is a tie (both strings have the same length), your method should remove the first string in the pair. If there is an odd number of strings in the list, the final value should be kept in the list.

Initial Contents of the ArrayList
Final Contents of the ArrayList
{"four", "score", "and", "seven", "years", "ago"} {"score", "seven", "years"}
{"here", "comes", "the", "sun", ":)"} {"comes", "sun", ":)"}

If you need reference to `ArrayList` methods, consult the cheat sheet! To review `ArrayList`s in general, check out Monday's slides!

# Exercise : Ferret Class

Define a Critter class called `Ferret`:

• A ferret should always infect when an enemy is in front of it, otherwise hop if possible, and otherwise randomly choose between turning left and turning right (each choice equally likely).
• Their appearance changes based on whether they recently attempted to infect. They initially display as "I=0" indicating that they have not attempted to infect recently. After an infect move, they should display as "I=5" and then on each subsequent move they should display a number counting down from the last time they infected. After an infect move, the display would change from "I=5" to "I=4", "I=3", "I=2", "I=1", and "I=0". It should then stay at "I=0". Notice, however, that it can go back to "I=5" in the middle of this process because it might infect again before reaching "I=0".
• The ferrets should be blue when they are displaying as "I=0" and red otherwise.

Use a Random object to make random choices but each Ferret should construct only one such object. As in assignment 8, fields must be declared private, fields initialized to a non-default value must be set in a constructor, and all updates to fields must occur in the getMove method.

To test, download ass8.zip, and add some ferrets to the simulation. As your ferrets encounter other critters, they should try to infect which will change their display. After you've completed Ferret.java, you can check your answer and one solution is here.

# 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.

For example:

```public static void main(String[] args) {
int[] list1 = {2, 4, 6};
int[] list2 = {1, 2, 3, 4, 5};
int[] combined = append(list2, list1);
// combined stores {1, 2, 3, 4, 5, 2, 4, 6}
}
```

You can review arrays in lab 7!

# 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.

For example:

```public static void main(String[] args) {
int[] array = {3, 8, 10, 1, 9, 14, -3, 0, 14, 207, 56, 98, 12};
int longest1 = longestSortedSequence(array);
// longest1 is 4 (because of -3, 0, 14, 207)

int[] array2 = {17, 42, 3, 5, 5, 5, 8, 2, 4, 6, 1, 19}
int longest2 = longestSortedSequence(array2);
// longest2 is 5 (because of 3, 5, 5, 5, 8)

```

You can review arrays in lab 7!

# 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!