University of Washington, CSE 142

Lab 5: While Loops, Random, Boolean and Midterm 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:

Cumulative algorithms

Exercise : repl practice-it

Exercise : longestName practice-it

Write a method named longestName that reads names typed by the user and prints the longest name (the name that contains the most characters) in the format shown below. Your method should accept a console Scanner and an integer n as parameters and should then prompt for n names.

A sample execution of the call longestName(console, 4) might look like the following:

name #1? roy
name #2? DANE
name #3? sTeFaNiE
name #4? Erik
Stefanie's name is longest

Try to solve this problem in Practice-It: click on the check-mark above!

Fencepost Loops

A fencepost loop is a common algorithmic pattern where you want to perform N tasks with N-1 things between them. It's like a fence with N posts with N-1 wires between the posts.

To achieve this, place one "post" outside your loop, then alternate between "wires" and "posts" inside the loop.

Example:

System.out.print(1);                 // |==|==|==|==| fence
for (int i = 2; i <= 5; i++) {
    System.out.print(".." + i);      // 1..2..3..4..5
}

Exercise : printFactors practice-it

Random methods

To use these methods, you need a variable of type Random in scope:

Random randy = new Random();
int aRandomNumber = randy.nextInt(10);  // 0-9
Method name Returns...
nextInt() a random integer
nextInt(max) a random integer between 0 (inclusive) and max (exclusive)
nextDouble() a random real number between 0.0 and 1.0
nextBoolean() a random boolean value: true or false

Exercise : Random expressions

Fill in the boxes to produce expressions that will generate random numbers in the provided ranges. Assume that the following Random variable has been declared:

Random rand = new Random();
Example: a random integer from 1 to 5 inclusive: rand.nextInt(5) + 1
a random integer from 0 to 3 inclusive: rand.nextInt(4)
a random integer from 5 to 10 inclusive: rand.nextInt(6) + 5
a random integer from -4 to 4 inclusive: rand.nextInt(9) - 4
a random even integer from 16 to 28 inclusive:
(Hint: To get only even numbers, scale up.)
rand.nextInt(7) * 2  + 16

The boolean type

The boolean type represents logical values of true or false. Combine boolean expressions with logical operators && (and), || (or), and ! (not).

Example:

boolean test1 = 7 < 10;            // true
boolean test2 = (1 == 2);          // false
if ((test1 || test2) && 2 + 2 != 5) {
    System.out.print("hello");     // output: hello
}

String methods with boolean results

Method name Description
string.equals(string) whether the two strings are identical
string.equalsIgnoreCase(string) whether the two strings are identical, ignoring capitalization
string.startsWith(string) whether this string begins with the characters of the given string
string.endsWith(string) whether this string ends with the characters of the given string
string.contains(string) whether the characters of the given string occur within this string
String name = "Professor Smith";
if (name.startsWith("Prof")) {
    System.out.println("When are your office hours?");
}

Exercise : Boolean Expressions

Write the result of each expression as either true or false, given the following variables.

int x = 12;
int y = 7;
int z = 28;
String s = "mid term";
x < 14
true
!(x % 2 < 1)
false
x < y || x < z
true
z / x < x / y * x
true
s.length() == y
false
s.toUpperCase().equals("MID TERM")
true
!s.equals("mid term") || x * y != z
true
s.substring(z / x).length() > y
false

while Loops

A while loop repeats indefinitely until a given condition is met.

while (test) {
    statement(s);
}

Example:

int num = 1;
while (num < 5) {
    System.out.print(n + " ");     // output: 1 2 3 4
    n++;
}

Exercise : while loop basics

Consider the following loop.

int x = 1;
System.out.print(x);
while (x < 100) {
    x = x + x;
    System.out.print(", " + x);
}
How many times does the code in the while loop execute? 7
What output is produced by the overall code? 1, 2, 4, 8, 16, 32, 64, 128

Exercise : while loop mystery practice-it

Fill in the boxes at right with the output produced by each method call.

public static void mystery(int x) {
    int y = 1;
    int z = 0;
    while (2 * y <= x) {
        y = y * 2;
        z++;
    }
    System.out.println(y + " " + z);
}
mystery(1);
1 0
mystery(6);
4 2
mystery(19);
16 4
mystery(39);
32 5
mystery(74);
64 6

Exercise : assertions practice-it

Identify whether each assertion is always/never/sometimes true at each point.

x > y z == 0 x == y
A
B
C
D
E
public static void mystery(int x, int y) {
    int z = 0;

    // Point A
    while (x != y) {
        // Point B
        z++;

        if (x > y) {
            // Point C
            x = x / 10;
        } else {
            // Point D
            y = y / 10;
        }
    }

    // Point E
    System.out.println(x + " " + y + " " + z);
}
	

You can also solve this problem in Practice-It by clicking on the check-mark above.

Midterm exam review

The CSE 142 midterm exam will be similar to the format of the practice exams. The exam will be made up of the following kinds of problems:

To solve each problem, you will need to use various concepts and syntax taught throughout the course so far, such as System.out.println, expressions, variables, parameters, return, if/else, for/while loops, Scanner, and Random. Part of the challenge is in figuring out which tools to use and how to use them together to solve the problem at hand.

Exercise : Expressions practice-it

For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type (e.g., 7.0 rather than 7 for a double, Strings in quotes).

4 * (2 + 4) - 3 * 5
9
54 % 10 + 8 * 3 % 9
10
3 * 2 + 4 + "+" + 2 + 3 * 4
"10+212"
2.3 * 3 + 19 / 5 / 2 + 6.0 / 5
9.1
108 / 20 * 3 / 4 / 2.0 + 1.0 / 2
2.0

Exercise : Parameter Mystery practice-it

Exercise : if/else mystery practice-it

Consider the following Java code.

public static void ifElseMystery(int a, int b) {
    if (a < b) {
        a = a * 2;
    }
    if (a > b) {
        a = a - 10;
    } else {
        b++;
    }
    System.out.println(a + " " + b);
}

Fill in the boxes with the output produced by each of the method calls.

ifElseMystery(10, 3);
0 3
ifElseMystery(6, 6);
6 7
ifElseMystery(3, 4);
-4 4
ifElseMystery(4, 20);
8 21

Exercise : while loop mystery practice-it

Fill in the boxes at right with the output produced by each method call.

public static void mystery4(int n) {
    int x = 1;
    int y = 2;
    while (y < n) {
        if (n % y == 0) {
            n = n / y;
            x++;
        } else {
            y++;
        }
    }
    System.out.println(x + " " + n);
}
mystery4(2);
1 2
mystery4(5);
1 5
mystery4(24);
4 3
mystery4(28);
3 7

Exercise : hopscotch practice-it

Write a method named hopscotch that accepts an integer parameter for a number of "hops" and prints a hopscotch board of that many hops.

For example, the call hopscotch(3); would produce the following output:

   1
2     3
   4
5     6
   7
8     9
   10

Try to solve this problem in Practice-It: click on the check-mark above!

Exercise : season practice-it

Exercise : lastDigit practice-it

Exercise : firstDigit practice-it

Exercise : makeGuesses practice-it

Write a method named makeGuesses that will output random numbers between 1 and 50 inclusive until it outputs one of at least 48. Output each guess and the total number of guesses made. Below is a sample execution:

guess = 43
guess = 47
guess = 45
guess = 27
guess = 49
total guesses = 5

Try solving this problem in Practice-It! from the link above.

Exercise : hasMidpoint practice-it

Write a method hasMidpoint that accepts three integers as parameters, and returns true if one of the numbers is the midpoint of the other two and returns false otherwise.

For example, the call hasMidpoint(3, 7, 5) would return true because one of the parameters (5) is the midpoint of the other two (3 and 7).

Try to solve this problem in Practice-It: click on the check-mark above!

Exercise : before practice-it

Write a method before that takes as parameters two month/day combinations and that returns whether or not the first date comes before the second date (true if the first month/day comes before the second month/day, false if it does not). The method will take four integers as parameters that represent the two month/day combinations.

The first integer in each pair represents the month and will be a value between 1 and 12 (1 for January, 2 for February, etc, up to 12 for December). The second integer in each pair represents the day of the month (a value between 1 and 31). One date is considered to come before another if it comes earlier in the year.

Solve this problem in Practice-It by clicking on the check-mark above.

Exercise : sameDashes practice-it

Write a method sameDashes that takes two strings as parameters and that returns whether or not they have dashes in the same places (returning true if they do and returning false otherwise). For example, below are four pairs of strings of equal length that have the same pattern of dashes. Notice that the last pair has no dashes at all.

string 1:    "hi--there-you."    "-15-389"    "criminal-plan"    "abc"
string 2:    "12--(134)-7539"    "-xy-zzy"    "(206)555-1384"    "9.8"
To be considered a match, the strings must have exactly the same number of dashes in exactly the same positions. The Strings might be of different length.

Solve this problem in Practice-It by clicking on the check-mark above.

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!