# Whiling away the lab

### Week of Wednesday, 5 October, 2005

Home | Resources | Homeworks | Slides | Labs | Contacts | Submit | Forums

## Objective

Being able to repeatedly execute statements of interest is a powerful programming mechanism. In this laboratory you will gain practice with the Java while looping statement.

This lab is a bit on the long side.  If you find yourself spending a lot of time on one part, ask a TA for help -- that's why they are there!

## Key Concepts

• while statement
• Common looping problems

## Getting Started

Using the procedures in the previous laboratories (i.e. right-click on the link and select "save as"), copy the files SeriesSum.java, IntervalSum.java, Upper.java, CharacterCounting.java, One.txt and Two.txt for your manipulation.  All four of the Java files need to be submitted for this lab.

## Determining sums of numbers

The first two while examples are concerned with computing sums of consecutive numbers. Although simple in nature, they illustrate nicely while loop behavior.

• Open the file SeriesSum.java.

• Consider the following while loop-based program that displays the sum of the integers in the range 1 maxNumber, where maxNumber is a user-supplied positive value. If maxNumber is 4, then the program displays the sum of 1 + 2 + 3 + 4, which is 10. The program contains one logic error (bug). Attempt to find it. A common debugging technique is to step through code manually (i.e., pretend you are the computer). Try three stepping through times – using in turn the values 1, 3, and 4.

• If you cannot find the error in the program, you should run it using different input values to see what is actually happening (e.g., 1, 3, and 4).  If that does not help, as a TA for assistance.

• Once the bug is found, fix it.

• Run the program using the values 1, 3, 4, -5, and 0. Does the program work correctly now? Once it is correct, submit it.

• Close program SeriesSum.java.

• Open the file IntervalSum.java. The intended purpose of IntervalSum.java is to calculate the sum of integers from a user-specified interval minNumbermaxNumber. Thus, IntervalSum.java is a generalization of SeriesSum.java, whose minNumber is always 1.

• As written, IntervalSum.java just prompts its users for the two values and checks that the extracted inputs are sensible. The program does not define the index variable whose value repeatedly takes on the numbers in the interval nor does it contain the loop that sums those numbers. Using the code from SeriesSum.java as a model, add a while loop that sums the numbers from the user-specified interval.

• Complete the program and compile it. Test the program to make sure it is working correctly.

• To test your program some more – complete the comments at the end of the program to show the result of runs using the following inputs. In your comments report both the expected and actual results

• 1 and 4
• -4 and -1
• -3 and 3
• 5 and 5
• 8 and 6

• Submit program IntervalSum.java.

• Close program IntervalSum.java.

## Text conversion

Often programs analyze text to see if it has some particular property. The next example program counts the number of uppercase letters in the text that it extracts. The program extracts its values from the standard input, which by default comes from the keyboard.  You will need to add the code so that the program also counts the total number of characters in the input.

• Open the program Upper.java.

• Examine the program to get a sense of how it accomplishes its task.

• The outer while loop condition is stdin.hasNext().  This means that while there is still input to be read in from the keyboard, this method will return true.  When there is no more input to be read in (i.e. when the user enters Ctrl-Z), it will return false.

• The first line in the outer while loop creates an input object which holds the current line read in from the keyboard.

• An inner while loop iterates through this input String so that it can analyze each individual character.

• For each character, if it is upper case, then the numberUpperCase variable is incremented.  This is done via a call to the Character.isUpperCase() method.

• Either way, i is incremented, as it is the counter variable for the inner while loop.

• Compile and run the program. It is important to observe that the program does not issue a prompt to the user to start supplying text. The program just waits silently for its input.  This is why we always put a legend in our programs (note that you don't have to for this lab).

• Provide the following text as input. When finished, you need to signal the program that you are done supplying standard input. On Windows-based PCs, a line consisting solely of a ctrl-z followed by enter produces the signal; most other systems often use ctrl-d followed by enter.

Java is great!
This course is FANTASTIC.
This Line Has a Lot of Uppercase Letters

• Modify the program to count also the total number of characters (including spaces and punctuation). The modification requires an additional counter variable. When defining the variable, provide a comment that justifies its initial value. This new variable should be incremented once per non-end of stream value.

• Test your program. Once it is completed correctly, submit it.

• Close program Upper.java.

## Using Input File Streams

Often programs need to read and write data files. In this exercise, you will learn to use the Scanner class to read from a file instead of reading from the keyboard. Other types of file processing will be considered later.

• Open the program CharacterCounting.java. The intended purpose of this program is to count the number of characters in a user-specified file.

• CharacterCounting.java first prompts its user for the name of the file and creates a Scanner object filein from the passed filename.  Note how the new Scanner object is created:

Scanner filein = new Scanner( new File(filename) );

This creates a new Scanner object called filein.  But instead of passing System.in to the constructor, we pass in new File(filename).  This tells the Scanner constructor to start reading from the specified file instead of from the keyboard.  This is using the File class, which we will see more of later.  The file class is in the java.io library, so the program also has the following at the top:

import java.io.*;

The filein Scanner object operates the same as the other Scanner objects we've been using.  In other words, you can still use next(), nextInt(), nextDouble(), etc., to read in values from the file.

• You may notice that the main() method is defined slightly differently in this program.  In particular, it is defined as:

public static void main(String[] args) throws IOException {

This deals with something called exceptions, which we are not going over yet.  For now, just remember that if you create a new File object (such as is done with the fileIn Scanner object), you have to put throws IOException after the arguments for the main() method.

• CharacterCounting.java also defines a variable numberCharacters whose value represents the number of characters extracted so far.  Because when it is defined no characters have been read from the file, it is initialized to 0.

• Using the code from Upper.java as a model, add code to CharacterCounting.java that counts the number of characters in the file.

• Compile and run the program trying data sets One.txt and Two.txt. Make sure you understand why the program produced its output.

• Once CharacterCounting.java is completed correctly, submit it.

• Close program CharacterCounting.java.

## Finishing up

• Copy any files you wish to keep to your home directory.

• Delete all of the files you copied or created on the laboratory machine.