University of Washington, CSE 142

Lab 10: 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

Today's lab

Goals for today:

You earn 1 point for each lab that you attend/show up on time for. Receiving credit for CSE 190 requires attending 8-10 labs. Please check that all your attendance records are correct on Canvas!

If you believe there is a problem with one of your scores, please email Price Ludwig at pludwig@cs.washington.edu.

Exam Tips

Reference mysteries

Reference mysteries test your understanding of reference semantics and value semantics. Review the difference in lab 8, slide 12!

On the following slide, write the output resulting from the execution of each corresponding line of code:

Note: Remember that printing arrays using Arrays.toString() prints using [], not {}.

Exercise : reference mystery practice-it

    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 practice-it

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 practice-it

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 : Groceries practice-it

Write a method name groceries that accepts as its parameter a Scanner holding an input file. The data in the file represents grocery items purchased along with their price and their discount category. Your method should compute and return a real number representing the total cost of the grocery items.

Each item is represented by three tokens: (1) the name of the item (a single word), (2) its discount category ("red" (10% off full price), "blue" (25% off full price), or "none" (no discount)), and (3) its full price. The casing of the discount category is not guaranteed (for example, we could see "red", "RED", "rED", "rEd", or any other casing of the word "red").

Example input:
avocado RED 1  blueberries none 5 milk blue 
   2.00       cream                   red 1.00    cereal None 1.29
This should return 9.59.

Exercise : reverseLines practice-it

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 practice-it

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?

Date class

Suppose you are given a class named Date with the following contents:

// A Date stores a month and day of the (non-leap) year.
public class Date {
    private int month;
    private int day;

    // constructs a new Date with the given month/day
    public Date(int m, int d)

    // returns the fields' values
    public int getMonth()
    public int getDay()

    public int daysInMonth()
    public void nextDay()
    public String toString()

    ...
}

Exercise : Date daysTillXmas practice-it

Exercise : Grasshopper practice-it

Write a class Grasshopper that extends the Critter class. A Grasshopper sits still until it gets into a fight. Once it fights, it celebrates its victory by doing a "hop".

A "hop" consists of moving NORTH a certain number of times, then SOUTH the same number of times, then WEST one time. The hops starts with a height of 1 (N, S, W), but each subsequent fight causes the next hop to be larger by one. The second hop is: (N, N, S, S, W). After finishing the hop, the Grasshopper sits idle again until it gets into another fight.

If a Grashopper is sitting still, it fights with Attack.ROAR. If a Grasshopper gets into a fight in the middle of a hop (while it is not sitting still), it always returns Attack.FORFEIT.

Example sequence of moves:

CCCC (fights) NSWCCC (fights) NNSSWCCCCCCC (fights) NNNSSSWCC ...

Exercise : append practice-it

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 practice-it

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!