University of Washington, CSE 142 (190)

Lab 5: while loops, Strings, and fencepost loops

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

lab document created by Whitaker Brand and Marty Stepp

Today's lab

Goals for today:

Recall: String Methods

Method name Description
charAt(index) character at given index
indexOf(str) index where the start of the given String appears in this string (-1 if not found)
length() number of characters in this String
replace(str1, str2) a new string with all occurrences of str1 changed to str2
substring(index1, index2)
or substring(index1)
the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs till end of string
toLowerCase() a new string with all lowercase letters
toUpperCase() a new string with all uppercase letters

Exercise : String Expressions

Write the results of each expression with Strings in "quotes" and characters in single quotes ('a')

//       index 0123456789012345
String str1 = "Frodo Baggins";
String str2 = "Gandalf the GRAY";
str1.length()
13
str1.charAt(7)
'a'
str2.charAt(0)
'G'
str1.indexOf("o")
2
str2.toUpperCase()
"GANDALF THE GRAY"
str1.toLowerCase().indexOf("B")
-1
str1.substring(5)
" Baggins"
str2.substring(3, 14)
"dalf the GR"
str2.replace("a", "oo")
"Goondoolf the GRAY"
str2.replace("gray", "white")
"Gandalf the GRAY"
"str1".replace("r", "range")
"strange1"

Exercise : Getting textbook code files

We are once again going to download a program from the textbook that we will use for a debugging exercise. To do so, follow these steps:

  1. Go to the class web page.
  2. Click on the "textbook" tab.
  3. Find the section labeled "Code Files" and click on the "code files" link.
  4. This will bring you to a directory listing that includes an entry for each chapter. Click on the link for "ch4".
  5. You want to download and save the file Hailstone.java. Right-click on the file name and choose the option to save the link in whatever folder you have been using for lab work.
  6. Compile and run Hailstone.java in jGRASP.

Exercise : jGRASP Debugger

We are going to practice setting stops and continuing execution. We will explore Hailstone.java. This program computes a sequence known as a hailstone sequence. This is related to an unsolved problem in mathematics known as the Collatz Conjecture.

To complete these problems, you will want to set breakpoints and to use the "Resume" button that resumes execution. The "Resume" button is the one that uses a standard "play" icon (the sixth one from the left below):

continued on the next slide...

Exercise - jGRASP Debugger

The first call on the method asks it to compute the sequence starting with the value 7. Set a stop that will allow you to determine the first five values that the variable value takes on not counting the initial value of 7.

Initial 7
next value
22
next value
11
next value
34
next value
17
next value
52

continued on the next slide...

Exercise - jGRASP Debugger

You should still be in the middle of the first execution of the method. Clear your old stop by clicking on it a second time and set a stop for the second method call in main. Then resume execution. You should end up back in main just before the second call is made.

Now we want to determine the sequence of values that the variable min takes on in this second call. It is initialized to the first value of 7 and is reset when a new minimum is encountered. Set a stop that will allow you to determine the first four values that the variable min takes on not counting the initial value of 7.

Initial 7
next value
5
next value
4
next value
2
next value
1

Exercise : while loop basics

Consider the following loop.

int x = 1;
System.out.print(x);
while (x < 100) {
    x = x + x;
    System.out.println(", " + x);
}

How many times does the code in the body while loop above execute? 7

What output is produced? 1, 2, 4, 8, 16, 32, 64, 128

Exercise : while loop mystery

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

public static void mystery(int x, int y) {
    int z = 0;
    while (x % y != 0) {
        x = x / y;
        z++;
        System.out.print(x + ", ");
    }

    System.out.println(z);
}
mystery(25, 2);
12, 1
mystery(32, 4);
0
mystery(10345, 10);
1034, 103, 10, 3
mystery(63, 2);
31, 15, 7, 3, 1, 0,
		6

Exercise : while loop mystery

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

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

Exercise : while loop mystery

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

public static void mystery3(int x) {
    int y = 0;
    while (x % 2 == 0) {
        y++;
        x = x / 2;
    }
    System.out.println(x + " " + y);
}
mystery3(19);
19 0
mystery3(42);
21 1
mystery3(48);
3 4
mystery3(40);
5 3
mystery3(64);
1 6

Exercise : repl practice-it

Exercise : printLetters practice-it

Exercise : printLetters - answer

public static void printLetters(String text) {
    if (text.length() > 0) {
        System.out.print(text.substring(0, 1));   // fencepost
        for (int i = 1; i < text.length(); i++) {
            System.out.print("-" + text.substring(i, i + 1));
        }
        System.out.println();   // to end the line of output
    }
}

Exercise : lastDigit practice-it

Exercise : firstDigit practice-it

Exercise : season practice-it

Exercise : printAverage practice-it

Exercise : digitSum practice-it

Exercise : digitSum - solution

public static int digitSum(int n) {
    n = Math.abs(n);            // handle negatives
    int sum = 0;
    while (n > 0) {
        int lastDigit = n % 10;
        sum = sum + lastDigit;  // add last digit to sum
        n = n / 10;             // remove last digit from n
    }
    return sum;
}

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 solving this problem in Practice-It: click on the check-mark above!

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!

Exercise : Syntax errors

Exercise - answer

  1. line 5: nextString should be next
  2. line 9: string should be String
  3. line 9: name should not be in quotes
  4. line 10: Whitaker should be in quotes
  5. line 10: cannot compare strings with ==; must use .equals
  6. line 13: cannot call replace without specifying a string object (name)
  7. line 14: toUppercase should be toUpperCase
  8. line 14: name. should come before toUpperCase, not passed as a parameter to it
  9. line 14: must say name = to store the result of toUpperCase
  10. line 15: must say name = to store the result of substring
  11. line 16: must use parentheses () when calling length

Exercise - Corrected version

public class StringOops {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.print("Type your name: ");
        String name = console.next();
        process(name);
    }

    public static void process(String "name") {
        if (name.equals("Whitaker")) {
            System.out.println("You must be really awesome.");
        }
        name = name.replace("a", "e");
        name = name.toUpperCase();
        name = name.substring(0, 3);
        System.out.println(name + " has " + name.length() + " letters");
    }
}

Exercise : ProcessName

Copy/paste and save this program in jGRASP, then go to the next slide.

import java.util.*;  // for Scanner

public class ProcessName {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.println("Type your name: ");
        
        // your code goes here
        
        System.out.println("Your name is: " + name);
    }
}

Exercise - code to add

Exercise - answer

Exercise : ProcessName2

Modify your ProcessName program so that it re-prompts until the user types a name that is at least 5 letters total in length and has at least one space in it. Example:

Type your name: Joe
Error, must be at least 5 chars with a space.
Type your name: O K!
Error, must be at least 5 chars with a space.
Type your name: what
Error, must be at least 5 chars with a space.
Type your name: Tyler Durden
Your name is: Durden, T.

Exercise - answer

import java.util.*;  // for Scanner

public class ProcessName2 {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.println("Type your name: ");
        String name = console.nextLine();
        
        while (name.length() < 5 || name.indexOf(" ") < 0) {
            System.out.println("Error, must be at least 5 chars with a space.");
            System.out.println("Type your name: ");
            name = console.nextLine();
        }
        
        int space = name.indexOf(" ");
        String first = name.substring(0, space);
        String last = name.substring(space + 1, name.length());
        String firstInitial = first.substring(0, 1);
        name = last + ", " + firstInitial + ".";
        System.out.println("Your name is: " + name);
    }
}

Exercise : printFactors practice-it

Exercise : swapPairs 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 Chapter 5 and try to solve them!