CISC 1115
Introduction to Programming Using Java
Lecture #9
Loops (Iteration)


Reading from the Text

Chapter 6

while (Condition-based) Loops

Overview

Initial Values of the Variables in the Loop Header

'Stuffing' Initial Values to Force the First Iteration

'Priming the pump'

File & Keyboard I/O Using a Loop

Header Values

We've been doing this for quite some time (from the beginning actually)

Program 9.1 (header value from file)

Write a program that reads an integer acting as a header value from a file, then reads in that many integers and prints them out
import java.io.*;
import java.util.*;

public class HeaderValue {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(new File("numbers.text"));

                int howMany = scanner.nextInt();

                for (int i = 1; i <= howMany; i++) {
                        int number = scanner.nextInt();
                        System.out.println(number);
                }
        }
}

Trailer Values

Program 9.2 (trailer value from file)

Write a program that reads words (strings) from a file, until the 'word' **** is input, printing the words as they are read in.

import java.io.*;
import java.util.*;

public class TrailerValue {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(new File("words.text"));

                String name = scanner.next();	// priming the pump
                while (!name.equals("****")) {
                        System.out.println(name);
                        name = scanner.next();
                }
        }
}

Program 9.3 (trailer value from keyboard)

Write a program that prompts the user for exam grades (integers), until a negative number is input, printing the numbers as they are entered.

import java.util.*;

public class TrailerValue {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(System.in);

                System.out.print("Enter a number (-1 to quit): ");	// priming the punp
                int grade = scanner.nextInt();					//      "
                while (grade >= 0) {
                        System.out.println(grade);
                        System.out.print("Enter a number (-1 to quit): ");
                        grade = scanner.nextInt();
                }
        }
}

Notes

end-of-file Processing

Program 9.4 (reading to end-of-file)

Write a program that reads in integers from a file, printing them out as they are entered.

import java.io.*;
import java.util.*;

public class EOF {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(new File("numbers.text"));

                while (scanner.hasNextInt()) {
                        int number = scanner.nextInt();
                        System.out.println(number);
                }
        }
}

Notes

end-of-file and the Keyboard

Program 9.5 (reading to end-of-file from the keyboard)

Write a program that reads in integers from the keyboard, printing them out as they are entered.

import java.io.*;
import java.util.*;

public class EOF {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(System.in);

                System.out.print("number? ");
                while (scanner.hasNextInt()) {
                        int number = scanner.nextInt();
                        System.out.println(number);
                        System.out.print("number? ");
                }
        }
}

Notes

If We Have eof, Why Use Anything Else?

Reading to eof only works with the real end-of-file. There are times when we need to structure our data with sequences in the middle of our data stream, and when that happens, we need a header or trailer value.

Program 9.6 — Working with Structured Data I

Assume a data file needs to be created containing data of the following form: Design the format of the file, and write a program that reads in the data and prints it out to standard output

students.text

Weiss Gerald 1234 A 3212 B 0000 2023 Arnow David 5412 A 3523 C 6512 B 0000 2024 Sokol Dina 1234 B 0000 2025

Notes

import java.io.*;
import java.util.*;

public class ProcessStudentData {
        public static void main(String [] args) throws IOException {
                final String CODE_TRAILER_VALUE = "0000";

                Scanner scanner = new Scanner(new File("students.text"));

                while (scanner.hasNext()) {
                        String last = scanner.next();
                        String first = scanner.next();
                        System.out.println(last + "," + first);

                        String code = scanner.next();
                        while (!code.equals(CODE_TRAILER_VALUE)) {
                                String grade = scanner.next();
                                System.out.println("\t" + code + ": " + grade);
                                code = scanner.next();
                        }

                        int gradYear = scanner.nextInt();
                        System.out.println("Graduating in " + gradYear);
                        System.out.println();
                }
        }
}

Notes

Stdout

Weiss,Gerald 1234: A 3212: B Graduating in 2023 Arnow,David 5412: A 3523: C 6512: B Graduating in 2024 Sokol,Dina 1234: B Graduating in 2025

Program 9.7 — Working with Structured Data II

Assume a data file needs to be created containing data of the following form: Design the format of the file, and write a program that reads in the data and prints it out to standard output

Other Loop Examples

Program 9.8

Write a program that 'picks' a secret number and allows the user to guess the number, until (s)he guesses correctly.

import java.util.*;

public class GuessingGame {
        public static void main(String [] args) {
                Scanner scanner = new Scanner(System.in);

                final int theNumber = 4;

                System.out.println( "=== Pick a number game ===");

                System.out.print("Enter a number from 1 to 10: ");
                int theGuess = scanner.nextInt();

                while (theGuess != theNumber) {
                        System.out.println( "Nyah yah nyah nyah nyah.... try again");

                        System.out.print("Enter a number from 1 to 10: ");
                        theGuess = scanner.nextInt();
                }

                System.out.println( "You got it right!");
        }
}

Notes

Java's Standard Libraries

Java's API (Application Programmer Interface) — Class Documentation

Some of the more commonly-used packages;

Program 9.9

Same as program 9.5, but uses Random.nextInt to choose a random secret number between 1 and 10

Random Number Generators with a Seed

Creating and Printing Tables

Program 9.10

Print the 10 x 10 multiplication table

Notes

public class MultiplicationTable {
        public static void main(String [] args) throws Exception {
                for (int i = 1; i <= 10; i++) {
                        for (int j = 1; j <= 10; j++)
                                System.out.print(i * j + " ");
                        System.out.println();
                }
        }
}

Stdout

1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100

Formatting Tabular Output

Program 9.11

Redo Program 9.10 in a nice, tabular fashion
public class MultiplicationTable {
        public static void main(String [] args) throws Exception {
                for (int i = 1; i <= 10; i++) {
                        for (int j = 1; j <= 10; j++)
                                System.out.printf("%3d ", i * j);
                        System.out.println();
                }
        }
}

Stdout

1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100

The printf Method

Eliminating The Nested Loops Using a Method

Program 9.12 — Multiplication Table

Redo Program 9.11 using a method to print a row in the table
public class MultiplicationTable {
        public static void main(String [] args) throws Exception {
                for (int i = 1; i <= 10; i++)
                        doOneRow(i);
        }

        public static void doOneRow(int i) {
                for (int j = 1; j <= 10; j++)
                        System.out.printf("%3d ", i * j);
                System.out.println();
        }
}

eof and Line-oriented Input (nextLine)

Program P9.13 — Using a Line Scanner

Input, and then print, the data from a file with the following format:
last-name first-name course-codes …
last-name first-name course-codes …
…

Notes

import java.io.*;
import java.util.*;

public class LineScanner {
        public static void main(String [] args) throws IOException {
                Scanner fileScanner = new Scanner(new File("student.data"));

                while (fileScanner.hasNextLine()) {
                        String line = fileScanner.nextLine();
                        Scanner lineScanner = new Scanner(line);

                        System.out.println(lineScanner.next());         // last name
                        System.out.println(lineScanner.next());         // first name

                        while (lineScanner.hasNextInt()) {
                                int courseCode = lineScanner.nextInt();
                                System.out.println(courseCode);
                        }
                        System.out.println();
                }
        }
}

The do/while Loop

There is a third flavor of loop in Java — the do/while loop — (again derived from C/C++), whose frequency of usage is far less than either the for loop or the while loop. The basic syntax is:
do {
	loop body
} while(condition);
Notes

Applications of the do/while Loop

There are a few (very few) examples that are naturally expressed using a do/while (the zero iteration case is just too prevalent to ignore). A classic one is playing a game; for example our number guessing game. The game is played (the first time), and after it is over, the user is prompted as to whether they wish to play again. The natural and most straightforward to do this is via a do/while:
do {
	play the game
	…
	…

	System.out.print("Want to play again? ");
	String response = scanner.next();
} while (response.equals("Yes"));
Notes
Another application is within a particular sorting method … we will encounter it later.

Files used in this Lecture

Lab for this Lecture