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 Type Returns....
charAt(index) char the character at the given index
indexOf(str) int the index where the start of the given String appears in this string (or -1 if not found)
length() int the number of characters in this String
replace(str1, str2) String a new string with all occurrences of str1 changed to str2
substring(index1, index2)
or substring(index1)
String the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs till end of string
toLowerCase() String a new string with all lowercase letters
toUpperCase() String a new string with all uppercase letters
[an error occurred while processing this directive]

Exercise : Catching String method returns

Write the value of the variable as prompted. Put Strings in "quotes" and characters in 'single quotes'.

//       index 0123456789012345
String str1 = "Frodo Baggins";
String str2 = "Gandalf the GRAY";
String str3 = str2.replace("gray", "white") // str3    = ?
"Gandalf the GRAY"
str2.toLowerCase() // str2    = ?
"Gandalf the GRAY"
str2 = str2.toLowerCase() // str2    = ?
"gandalf the gray"
int index = str1.toLowerCase().indexOf("B") // index = ?
-1
[an error occurred while processing this directive]

Exercise : equalsIgnoreCase()

equalsIgnoreCase() is identical to .equals(), except it ignores the case of the Strings being compared.
Enter true or false for the following:

"abc".equalsIgnoreCase("abc");
true
"abc".equalsIgnoreCase("ABC");
true
"abc".equals("ABC");
false
"iLoveHalloween!".equalsIgnoreCase("iLoVeHaLlOwEeN!");
true
[an error occurred while processing this directive]

Cumulative algorithms

A cumulative algorithm involves incrementally accumulating a value by repeatedly adding, multiplying, dividing, etc., while storing the result in a variable.

Key aspects of a cumulative algorithm: A loop, and a variable declared outside the loop whose value is modified inside the loop.

Example: Cumulative algorithm to sum the numbers 1-100:
int sum = 0;                // safe default value, 0 doesn't affect a sum
for (int i = 1; i <= 100; i++) {
    sum = sum + i;
}
System.out.println(sum);    // 5050
[an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive]

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
}
[an error occurred while processing this directive]

while Loops

for loops are fantastic for when we know how many times we want to repeat something. But sometimes we won't know how many times we'll want to repeat something in advance! while loops repeat indefinitely while a given condition is true.

while (test) {
    statement(s);
}

Example:

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

Exercise : Password matching

How many times does "Wrong! Try again:" print for the following user inputs?
import java.util.*; // lets us use the Scanner

public class Password {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
    
        String password = "password"; // secure
        System.out.print("Enter your password: ");
        String input = console.next();
        
        while (!input.equals(password)) {
            System.out.print("Wrong! Try again: ");
            input = console.next();
        }
        
        System.out.println("Welcome to DefCon!");
    }
}

input: password

0

input: hello?   abc123   password

2

input: pswd   PASS   word?   sm39!#2   password

4
[an error occurred while processing this directive]

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 = 4;
    while (y <= x) {
        y = y + 4;
    }
    System.out.println(y);
}
mystery(1);
4
mystery(6);
8
mystery(19);
20
mystery(40);
44
[an error occurred while processing this directive] [an error occurred while processing this directive]

Checkpoint: Congratulations!

Nice job making it this far--labs are tough!

These next problems get a little more challenging as we explore earlier concepts further.

We put a lot of problems in here so that you have plenty to refer back to later when working on homework. Don't feel bad if you don't finish all of them--Brett can't finish them all in a 50 minute lab, either! :)

[an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive]

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!