5: Iteration

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

Counter-controlled repetition requires:

  1. A named control variable and initial value.
  2. A control variable increment.
  3. A condition that tests for the final value of the control variable.
  4. All of the above.

5.1: Iterating (Loops)

Objectives

At the end of the lesson the student will be able to:

  • Use while statements to repeat sections of code
  • Apply commonly-used looping patterns
  • Avoid common looping problems

5.1.1: Introduction to Loops

  • Loops are used to repeat sections of code
  • General loop structure:
    • Initialization code
    • Loop condition -- evaluated during the loop
    • Loop body
  • Java has 3 loop statement
  • while
    do-while
    for
    
  • However, you can use any loop statement and achieve the same result
  • Thus, I am only going to teach the simplest loop statement at this time
  • Later on we will look at the other loop statements

5.1.2: Coding while Statements

  • Use a while loop to repeat a section of code
  • Repetition continues as long as the loop test condition remains true
  • while loop Syntax:
  • //Initialization
    ...
    while (loopTest) {  //loop condition
       //loop body
       ...
    }
    
  • Initialization statements usually precede the while loop
  • Checks loopTest at start of every loop iteration
    • Continues as long as loopTest is true
  • Note that if the loop condition is initially false then the loop body never executes
  • Loop body can be a single statement or a block

5.1.3: Example Application: Play Again Program

  • The following application simulates the play of an exciting game
  • Note how the syntax matches the code
import javax.swing.JOptionPane;

public class PlayAgain {
    public static void main(String[] args) {
        String answer = "y";
        String msg = "Playing an exciting game!\n"
                     + "Do you want to play again? (y/n)";

        while (answer.equalsIgnoreCase("y")) {
            answer = JOptionPane.showInputDialog(msg);
        }

        String endMsg = "Thanks for playing!";
        JOptionPane.showMessageDialog(null, endMsg);
        System.exit(0);
    }
}
  • Which statement initializes the loop variables?
  • Which part is the loop condition?
  • Which part is the loop body?
  • Loops of this type are often called the main programming loop

5.1.4: while-Loop Operation

While flow chart

Programming Style: Placement of Braces

  • Different practices for placing curly braces in a loop statement
  • For the acceptable styles for this course see: Curly Braces

5.1.5: Summary

  • Loops are used to repeat sections of code
  • General loop structure:
    • Initialization code
    • Loop condition -- evaluated during the loop
    • Loop body
  • The while loop is the most basic repetition statement
    • Will look at other repetition statements later in the course
  • Many programs have a main program loop
  • Program repeats (iterates) until the user decides to exit

Exercise 5.1

  1. Label this exercise: Exercise 5.1
  2. Complete the following and record the answer any questions in your exercise5.txt file.

Specifications

  1. Update the guessing game program that follows to let the user make as many guesses as they choose.
  2. Submit your program along with your exercise5.txt file.

I suggest that you use the following code to get started.

import javax.swing.JOptionPane;

public class GuessingGame2 {
    public static void main(String[] args) {
        int guess = 0;
        String input = "";
        String output = "";

        String msg = "I'm thinking of a number between"
                     + " 1 and 10.\nCan you guess it?";
        input = JOptionPane.showInputDialog(msg);
        guess = Integer.parseInt(input);

        if (guess == 7) {
            output = "*** Correct! ***";
        } else {
            output = "Sorry, that is not correct.";
        }
        JOptionPane.showMessageDialog(null, output);

        System.exit(0);
    }
}

5.2: More Loops

Objectives

At the end of the lesson the student will be able to:

  • Use while statements to repeat sections of code
  • Apply commonly-used looping patterns
  • Avoid common looping problems

5.2.1: More About Loops

  • Loops provide more power to the programmer
  • Your programs can repeat sections of code
  • We will look at some common looping patterns
  • With the power of loops comes more problems
  • We will look at some of the common problems

5.2.2: Another Application: Accumulating Values

  • One common looping task is to calculates sums or products
  • For example, to sum the numbers from 0 through 4:
  • public class SumNums {
        public static void main(String[] args) {
            //Loop initialization
            int counter = 0;
            int sum = 0;
            while (counter < 5) { //loop condition
                //loop body
                sum = sum + counter;
                System.out.println("After adding "
                    + counter + " sum = " + sum);
                counter++; // adjust counter
            }
            System.out.println("Total sum = " + sum);
        }
    }
    
  • This is known as accumulating values
  • What would we change to compute the product of the numbers from 1 to 5?
  • What would we change to sum the even numbers from 1 through 10?
  • What would we change to sum the odd numbers from 1 through 10?

5.2.3: Looping Patterns

  • Let us look at some ways to use loops

Counter-Controlled Loops

  • Use this pattern when you know how many times to repeat a section of code
  • The key is a variable called the counter
    1. Initialize the counter variable to 0
    2. Set the loop condition to check for the maximum count
    3. Adjust the counter variable inside the body of the loop
  • For example:
public class Counter5 {
    public static void main(String[] args) {
        int count = 0; // initialize counter
        while (count < 5) { //loop condition
            //loop body
            System.out.println(count);
            count++; // adjust the counter
        }
        System.out.println("After loop count = " + count);
    }
}
  • A variation is to start at the maximum value and count down

Ask Before Repeating

  • Another pattern is to ask the user whether or not to repeat a loop
  • Often used to allow the user to control the flow of a program
  • For example:
import javax.swing.*;

public class SumAsker {
    public static void main(String[] args) {
        //Loop initialization
        double input = 0.0;
        double total = 0.0;
        int choice = 0;
        while (choice == 0) { //loop condition
            //loop body
            String data = JOptionPane.showInputDialog(
                "Enter a number");
            input = Double.parseDouble(data);
            total = total + input;
            choice = JOptionPane.showConfirmDialog(
                null, "Enter another number?");
        }
        JOptionPane.showMessageDialog(null,
            "Total: " + total);
        System.exit(0);
    }
}
  • For a long list, this approach can be tiring
  • Often time, a better solution is to use a sentinel-controlled loop

Sentinel-Controlled Loops

  • Use a sentinel when you can use input data to tell the program when to stop
  • Looping continues as long as the data value read is not a sentinel value
  • When a sentinel value is read, the loop exits
  • For example:
import javax.swing.*;

public class SumInput {
    public static void main(String[] args) {
        //Loop initialization
        double input = 0.0;
        double total = 0.0;
        while (input != -1) { //loop condition
            //loop body
            total = total + input;
            String data = JOptionPane.showInputDialog(
                "Enter a positive number or -1 to exit");
            input = Double.parseDouble(data);
        }
        JOptionPane.showMessageDialog(null,
            "Total: " + total);
        System.exit(0);
    }
}
  • input is the sentinel variable
  • The sentinel value is the number: -1
  • The program ends when the user enters the sentinel value

5.2.4: Common Loop Pitfalls

Infinite Loops

  • Common error: unintentional infinite loop
  • For example, what is wrong with the following code?
  • public class InfiniteLoop1 {
        public static void main(String[] args) {
            int count = 0;
            while (count < 10) {
                System.out.println(count); // trace
            }
        }
    }
    

Empty Statements

  • Remember that statements are terminated by a semicolon
  • Is the following a legal statement?
  • ;
  • Known as an empty or null statement
  • Empty statements are a common source of infinite loops
  • For example, what is wrong with the following code?
  • public class InfiniteLoop2 {
        public static void main(String[] args) {
            int count = 0;
            while (count < 10); {
                System.out.println(count); // trace
                count++;
            }
        }
    }
    

Off-By-One Errors

  • A common looping problem is the off-by-one error
  • Often a less-than is confused with a less-than-or-equal-to
  • For example, to sum the numbers between one and 10, what is wrong with:
  • public class OffByOne {
        public static void main(String[] args) {
            int sum = 0;
            int count = 1;
            while (count <= 10) {
                sum += count;
                count++;
            }
            System.out.println(sum);
        }
    }
    

Tracing Variables

  • One good way to discover loop errors is to trace key variables
  • Tracing variables means watching them change as the program executes
  • You can insert temporary output statements in your program
  • For instance, we had trace statements in the infinite loop examples above
  • What variables would we trace for the off-by-one error example?

5.2.5: Nested Loops

  • Often necessary to have one loop inside another
  • Following example shows this structure
  • Let's follow the execution sequence before checking the result
public class Nested {
    public static void main(String[] args) {
        int outer = 1;
        while (outer < 4) {
            System.out.println("outer = " + outer);
            int inner = 1;
            while (inner < 4) {
                System.out.println("  inner = " + inner);
                inner++;
            }
            outer++;
        }
    }
}
  • Which statements provide the trace to allow us to see the operation?

5.2.6: Summary

  • Loops are used to repeat sections of code
  • General loop structure:
    • Initialization code
    • Loop condition -- evaluated during the loop
    • Loop body
  • The while loop is the most basic repetition statement
    • Will look at other repetition statements later in the course
  • Several common uses of a loop
    • Counter-controlled loops
    • Ask Before Repeating
    • Sentinel-controlled loops
  • Several problems that can occur when using a loop
    • infinite loops: loops that "never" stop
    • Off-by-one errors: start or stop at a wrong value
  • Tracing variables is a good way to discover loop errors
  • It is legal code to have one loop nested inside another

Exercise 5.2

  1. Label this exercise: Exercise 5.2
  2. Complete the following and record the answer any questions in your exercise5.txt file.

Specifications

  1. Write a program that lists the numbers 1 through 10 and the square of the numbers.

5.3: More Control Statements

Objectives

At the end of the lesson the student will be able to:

  • Use switch statements for branching
  • Use do-while statements to control loops
  • Use for statements to control loops
  • Use break and continue statements with loops
  • In this section, we learn about the rest of Java's control statements
  • These statements do not add new capabilities
  • Just provide alternate ways of performing some tasks
  • Since Java code has them, you need to know how to use them

5.3.1: switch Statements

  • The switch statement provides an alternative to an if-else chain
  • Executes a section of code depending on value of a variable
  • General form:
  • switch (integerExpression) {
       case label1:
          statements
          break;
       case label2:
          statements
          break;
       ...
       case labeln:
          statements
          break;
       default:
          statements
          break;
    }
    
  • Keyword switch identifies the start of the switch statement
  • Expression in parenthesis is evaluated for comparison to each case label
    • integerExpression must evaluate to an integer
    • Otherwise a compilation error occurs
  • Within a switch statement, keyword case labels each entry point into the code
    • Code executes if integerExpression matches the case label value
    • Execution starts with the statement immediately following the match
  • Any number of case labels can be placed in any order
  • Any value that does not match starts executing with the statement after default
  • Execution continues until the end of the switch statement or a break statement
  • The break statement causes an immediate exit from the switch statement
  • Just as case identifies possible starting points, break determines end points

For Example:

import javax.swing.JOptionPane;

public class Switch {
    public static final int PARCEL_POST = 0;
    public static final int UPS = 1;
    public static final int FED_EX = 2;

    public static void main(String[] args) {
        String msg = "Enter a shipping option";
        String input = JOptionPane.showInputDialog(msg);
        int shippingOption = Integer.parseInt(input);

        String output;
        switch (shippingOption) {
            case PARCEL_POST:
                output = "Delivery in two weeks.";
                break;
            case UPS:
                output = "Delivery in three days.";
                break;
            case FED_EX:
                output = "Overnight delivery.";
                break;
            default:
              output = "It may never get there!";
        }
        JOptionPane.showMessageDialog(null, output);

        System.exit(0);
    }
}

  • Notice that each case other than the last contains a break statement
  • Ensures that the switch statement is exited after a matching case is found

When to Use switch Statements

  • You can only use switch statements with integer expressions
  • Inherently less useful than if-else statements
  • Syntax is no clearer than if-else statements
  • Thus, no real need to ever use a switch statement
  • One acceptable use is for a menu like that shown above

5.3.2: Conditional (Ternary) Operators

  • Provides a compact if-else structure
  • Syntax:
  • operand1 ? operand2 : operand3;
    
  • First operand must be a conditional expression that evaluates to true or false
  • If operand1 is true, return operand2; otherwise return operand3.

For Example

  • Following is an if-else statement
  • String outMessage;
    double celsius = 50;
    
    if (celsius >= 100) {
        outMessage = "Boiling!";
    } else {
        outMessage = "Not boiling";
    }
    
    System.out.println(outMessage);
    
  • Equivalent using the conditional operator
  • String outMessage;
    double celsius = 50;
    
    outMessage = (celsius > 100)
        ? "Boiling!"
        : "Not boiling";
    
    System.out.println(outMessage);
    

When to Use Conditional (Ternary) Operators

  • Rarely used in professional programing
  • Almost always better to use if-else statements

5.3.3: do-while Statements

  • Variation of the while loop
  • Syntax:
  • //Initialization
    ...
    do {
       //loop body
       ...
    } while (loopTest); //loop condition
    
  • Initialization code may precede loop body
  • Loop test is after the loop body
  • Loop must execute at least once (minimum of at least one iteration)
  • Use when you want to force a minimum of one iteration

Validity Checks

  • Can use do-while statements to filter user input
  • For example, assume we need a positive value from the user:
import javax.swing.*;

public class SumInputDo {
    public static void main(String[] args) {
        //Loop initialization
        double input = 0.0;
        do {
            //loop body
            String data = JOptionPane.showInputDialog(
                "Enter a positive number: ");
            input = Double.parseDouble(data);
            if (input < 0.0) {
                JOptionPane.showMessageDialog(null,
                    "You must enter a positive number",
                    "Input Data Error",
                    JOptionPane.ERROR_MESSAGE);
            }
        } while (input < 0.0); //loop condition
        JOptionPane.showMessageDialog(null,
            "Input: " + input);
        System.exit(0);
    }
}

When to Use do-while Statements

  • Rarely used in professional programming
  • Can accomplish the same control flow with a while loop
  • Sometimes used for validating user input, as shown above
  • Use it when you want to force a minimum of one iteration

5.3.4: for Statements

  • Provides a more compact loop
  • Syntax:
  • for (initializer; condition; increment) {
       //loop body
       ...
    }
    
  • Initialization, loop-test, and increment-expression are part of the syntax
  • initializer expression: defines the initial value used to control the loop
  • condition expression: determines when the loop will end
  • increment expression: evaluated at the end of each loop iteration
  • Statements to repeat are enclosed in curly brackets
  • Execution sequence as follows:
  1. When for statement reached -- initialization executes
  2. Check if condition is true
    • if true then continue with Step 3
    • Otherwise, continue with Step 6
  3. Execute block containing the loop body
  4. When end of loop body is reached, execute the increment
  5. Return to Step 2
  6. Loop is finished: continue with statements after the loop

Counter-Controlled-Loop Example

    public class CounterFor {
        public static void main(String[] args) {
            int count;
            for (count = 0; count < 5; count++) {
                System.out.println(count);
            }
        }
    }
    
  • Note that code is indented in the loop body for readability

Counting Down

  • Can also count downwards
  • Positive numbers step higher (+inf) and negative numbers step lower (-inf)
  • What is displayed with the following?
  • public class CountDown {
        public static void main(String[] args) {
            int count;
            for (count = 5; count > 0 ; count--) {
                System.out.println(count);
            }
        }
    }
    

When to Use for Statements

  • Very often used in professional programming
  • Especially useful for counter-controlled loops

5.3.5: break and continue Statements

  • break and continue statements transfer control to another part of a program
  • Within a loop break statements an immediate exit
  • Transfers control to statement following the loop
  • Provides a way to break out of an intentional infinite loop
  • public class BreakOut {
        public static void main(String[] args) {
            int count = 0;
            while (true) {
                count++;
                if (count == 3) continue;
                System.out.println(count);
                if (count >= 5) break;
            }
            System.out.println("After count= " + count);
        }
    }
    
  • continue statement transfers control to the loop condition
  • Causes the loop to skip the rest of the current iteration
  • When encountered in a loop, starts the next iteration of the loop immediately

When to Use break and continue Statements

  • Use break statements in switch statements only
  • Never use break in looping constructs
    • Poor coding habit
    • Should only have one exit point in a loop
  • In this course, you will never a need to write infinite loops
  • Do not need to use continue statements either
  • Can accomplish the same operation other ways

5.3.6: Summary

  • Java provides many control statements
  • Provide alternatives to the basic statements covered earlier
  • Of those covered today, most useful is the for loop
  • Provides a compact looping structure often used for counter-controlled repetition

Exercise 5.3

  1. Label this exercise: Exercise 5.3
  2. Submit all exercises for this lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in exercise5.txt.

Specifications

public class Counter5 {
    public static void main(String[] args) {
        int count = 0; // initialize counter
        while (count < 5) { //loop condition
            //loop body
            System.out.println(count);
            count++; // adjust the counter
        }
        System.out.println("After loop count = " + count);
    }
}
  1. Convert the above code to use a for loop rather than a while loop.
  2. Turn in the modified code along with your exercise5.txt file
  3. Record answers to the following questions in exercise5.txt.
  4. Q1: What is the chief advantage of using a for loop?

    Q2: The for loop seems most appropriate for which type of looping pattern?

5.4: Processing Strings

Objectives

At the end of the lesson the student will be able to:

  • Compare string equality
  • Use charAt() to extract characters from a string

5.4.1: More String Class Methods

  • Because strings are class types, most operations on strings use String class methods
    • One exception is assignment, which uses the equals operator
    • Another exception is concatenation, which uses the + sign

Previously Reviewed Methods

  • length(): Returns the length of the string
  • String s = "Hello";
    System.out.println(s.length());
    
  • charAt(int): Returns a char at the specified index.
  • toLowerCase(): Returns a new string with all characters in lowercase.
  • toUpperCase(): Returns a new string with all characters in uppercase.
  • trim(): Returns a new string with all whitespace removed from the beginning and end.

Some Other Commonly-Used Methods

5.4.2: Comparing String Equality

  • "==" does not act like you may think for String objects
  • "==" tests to see if the address of the two objects are the same
  • For example, enter the same word into both strings of the following:
import javax.swing.JOptionPane;

public class StringComparer {
    public static void main(String[] args) {
        String s1, s2;

        s1 = JOptionPane.showInputDialog("Enter string 1");
        s2 = JOptionPane.showInputDialog("Enter string 2");

        System.out.println(s1 == s2); // prints false
        System.out.println(s1.equals(s2));
        System.out.println(s1.equalsIgnoreCase(s2));

        System.exit(0);
    }
}
  • The reason is that the two strings, s1 and s2, refer to different objects
  • Two string objects in memory

  • Must use the equals() method to test if the String contents are equal
    • Use equals() when case matters
    • Use equalsIgnoreCase() to ignore case

5.4.3: Comparing Strings Lexicographically

  • Can also use the compareTo method to test String equality
  • String string1 = new String("Hello");
    String string2 = new String("Hello there");
    int n = string1.compareTo(string2);
    System.out.println(n);
    
  • In Unicode:
    • Digits are stored in order from 0 to 9
    • Letters of the alphabet are stored in order from A to Z
    • A blank precedes (is less than) all letters and digits
    • Digits come before lowercase letters
    • Lowercase letters come before uppercase letters
  • When two strings are compared lexicographically, their individual letter are compared a pair at a time
  • If no differences are found, the strings are equal
    • compareTo method returns a 0 (zero)
  • If a difference is found, string with the lower first letter is considered the smaller string
    • compareTo method returns a negative number if the Other string comes after this one
    • compareTo method returns a positive number if the Other string comes before this one
  • For example:
    • "Hello" is greater than "Good Bye" ('H' is greater than 'G')
    • "123" is less than "124" ('3' is less than '4')

5.4.4: Using charAt()

  • Method charAt(int) returns a character at the specified index
  • Using charAt(), we can improve our guessing game and use letters
import javax.swing.JOptionPane;

public class GuessingGame3 {
    public static void main(String[] args) {
        String input = "";
        String output = "";
        char letter = '\0';

        String msg = "I'm thinking of a letter between"
                     + " A and Z.\nCan you guess it?";
        input = JOptionPane.showInputDialog(msg);
        letter = input.charAt(0);

        if (letter == 'J') {
            output = "*** Correct! ***";
        } else {
            output = "Sorry, that is not correct.";
        }
        JOptionPane.showMessageDialog(null, output);

        System.exit(0);
    }
}
  • Also, we can process strings one character at a time using a loop
  • String msg = "Hello!";
    int index = 0;
    while (index < msg.length()) {
        System.out.println(msg.charAt(index));
        index++;
    }
    

5.4.5: Summary

  • You must use methods of the String object to compare two strings
  • Use equals when case matters
  • Use equalsIgnoreCase to ignore case
  • String method charAt() extracts characters from a string

Exercise 5.4

  1. Start a text file named exercise5.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 5.4
  4. Submit all exercises for this lesson in one file unless instructed otherwise
  5. Complete the following and record the answers to any questions in exerciseX.txt.

Specifications

  1. Write a single statement that compares the string in s1 to the string in s2 for equality of contents. Save your statement in exercise5.txt.
  2. Write a single statement that appends the string s2 to the string s1, using +=. Save your statement in exercise5.txt.
  3. Write a single statement that determines the length of the string in s1. Save your statement in exercise5.txt.
  4. Modify the following guessing-game program to correctly test the guess provided by the user. Save your modified program along with this weeks exercises.
import javax.swing.JOptionPane;

public class GuessingGame4 {
    public static final String correctWord = "Java";

    public static void main(String[] args) {
        String input = "";
        String output = "";

        String msg = "I'm thinking of a word with "
                     + correctWord.length()
                     + " letters.\nCan you guess it?";
        String guess = JOptionPane.showInputDialog(msg);

        // Insert test condition in place of true
        if (true) {
            output = "*** Correct! ***";
        } else {
            output = "Sorry, that is not correct.";
        }
        JOptionPane.showMessageDialog(null, output);

        System.exit(0);
    }
}

Wrap Up

    Reminders

    Due Next Class: A4: Tally Ho! (10/4/04)
    Exercise 5 and CodeLab Lesson 5 (10/4/04)

  • When class is over, please shut down your computer
  • You may complete unfinished exercises at the end of the class or at any time before the next class.
  • Instructions on submitting exercises are available from the HowTo's page.

Home | WebCT | Announcements | Schedule | Expectations | Course info
Help | FAQ's | HowTo's | Links

Last Updated: October 03 2004 @20:34:03