University of Washington, CSE 142

Lab 5: Strings, cumulative algorithms, while loops, fencepost loops

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:

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(4)
"o 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 : ProcessName practice-it

Copy/paste and save icon ProcessName.java 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.print("Type your name: ");
        
        // your code goes here
        
        System.out.println("Your name is: " + name);
    }
}

continued on the next slide ...

Exercise - code to add practice-it

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!

Exercise : Getting textbook code files

In this exercise we will download a program from the textbook for a debugging exercise.

  1. Go to the course web page and click the Textbook sidebar link.
  2. Find the section labeled Code Files and click the "code files" link.
  3. This will bring you to a listing of all chapters. Click the link for ch04.
  4. Download and save Hailstone.java. Right-click the file name and choose the option to Save the Link in the folder you have been using for lab work.
  5. Compile and run Hailstone.java in jGRASP.

Exercise : jGRASP Debugger

We are going to practice using the jGRASP debugger with Hailstone.java. This program computes a sequence of integers called a hailstone sequence. (This is related to an unsolved problem in mathematics known as the Collatz Conjecture.)

continued on the next slide...

Exercise - Values of value

# value
first value 7
second value 22
third value
11
fourth value
34
fifth value
17
sixth value
52

continued on the next slide...

Exercise - Values of min

# min
first value 7
second value
5
third value
4
fourth value
2
fifth value
1

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

Exercise : printFactors practice-it

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 : while loop mystery practice-it

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

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

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

Exercise : digitSum practice-it

Exercise : ProcessName2 practice-it

Modify your previous 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 : 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 the book and try to solve them!