Building Java Programs

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
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. Put Strings in "quotes".

//       index 0123456789012345
String str1 = "Frodo Baggins";
String str2 = "Gandalf the GRAY";
str1.length()
13
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 : while loop basics

How many times does the code in the 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 : 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

Exercise - code to add

Exercise - answer

Exercise : ProcessName2

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.print("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.print("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 : 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 : repl practice-it

Exercise : ZuneBug

The following code from Microsoft's Zune music player calculates today's date from the years/days passed since 1980. But all Zune players locked up on Jan 1 2009. Why? Download icon ZuneBug.java and modify it to fix the bug.

int days = getTotalDaysSince1980();   // pretend this method exists
int year = 1980;
while (days > 365) {                  // subtract out years
    if (isLeapYear(year)) {           // pretend this method exists
        if (days > 366) {
            days = days - 366;
            year++;
        }
    } else {
        days = days - 365;
        year++;
    }
}

Exercise : ZuneBug - answer

The bug occurs when the current year is a leap year and there are exactly 366 days left (i.e., if today is Jan 1 on a year after a leap year). The code gets stuck in an infinite loop with days == 366 because the while test is true but the if (days > 366) is false. Here is a fixed version:

int days = getTotalDaysSince1980();   // pretend this method exists
int year = 1980;
while (days > 365 || (isLeapYear(year) && days > 366)) {
    if (isLeapYear(year)) {
        days = days - 366;
    } else {
        days = days - 365;
    }
    year++;
}

Exercise : printLetters practice-it

Consider the following flawed method printLetters, which accepts a String as its parameter and attempts to print the letters of the String, separated by dashes. For example, the call of printLetters("Rabbit") should print R-a-b-b-i-t .

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

What is wrong with the code? Paste the code in Practice-It! and fix 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 : printFactors practice-it

Write a method named printFactors that accepts an integer as its parameter and uses a fencepost loop to print the factors of that number, separated by the word "and". For example, the call printFactors(24) should print as the following output:

1 and 2 and 3 and 4 and 6 and 8 and 12 and 24

You may assume that the parameter value passed is greater than 0.

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!