LABORATORY 8

Whiling away the lab

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.

Key Concepts

·         while statement

·         Common looping problems

8.1      GETTING STARTED

·         Using the procedures in the previous laboratories, copy the files SeriesSum.java, IntervalSum.java, Upper.java, CharacterCounting.java, One.txt and Two.txt for your manipulation.

8.1      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.

·         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.

 

// Name:

// Email id:

 

import java.util.*;

 

public class SeriesSum {

 

   public static void main(String[] args) {

 

      // determine the maximum number in the series to sum

 

      Scanner stdin = new Scanner(System.in);

 

      System.out.print("Enter a positive number: ");

      int maxNumber = stdin.nextInt();

     

      System.out.println();

 

      // make sure user followed the instructions

 

      if ( maxNumber < 0 ) {

         // the user did not follow the instructions – print message and exit

 

         System.out.println("Unacceptable number: " + maxNumber + " program exits.");

         System.exit(0);

      }

 

      // user followed instructions sum the numbers from 1 to maxNumber

      // in the series

 

      int sum = 0;           // keeps track of the running total of the

                             // terms. Nothing has been added so sum is 0

       

      int currentNumber = 1; // keeps track of current term of interest

                            // in the series. First term is 1.

 

      while (currentNumber <= maxNumber) {

         // add next term to the running total

         sum = sum + maxNumber;

         // add 1 to get term of interest

         ++currentNumber;

      }

 

      // running total is now the actual total

 

      System.out.println("The sum from 1 to " + maxNumber + " is " + sum);

   }

}

 

·         Open the file SeriesSum.java. The file contains the preceding program.

·         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).

·         The mistake takes place in updating sum. Variable sum is not being increased by the right amount. Modify the code to increment sum appropriately.

·         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 intervals of numbers always started with 1.

import java.util.*;

 

public class IntervalSum {

 

   public static void main(String[] args){

 

      // determine the minimum and maximum number in the series to sum

 

      Scanner stdin = new Scanner(System.in);

 

      System.out.print("Enter a number: ");

      int minNumber = stdin.nextInt());

 

      System.out.print("Enter a larger number: ");

      int maxNumber = stdin.nextInt());

 

      System.out.println();

 

      // make sure user followed the instructions

 

      if ( maxNumber < minNumber ) {

         // the user did not follow the instructions – print message and exit

 

         System.out.println("Unacceptable interval: " + minNumber

             + " ... " + maxNumber + " program exits.");

         System.exit(0);

      }

 

      // user followed instructions sum the numbers from 1 to maxNumber

      // in the series

 

     int sum = 0;           // keeps track of the running total of the

                            // terms. Nothing has been added so sum is 0

       

 

     // ******************* add code here **************************

 

     // running total is now the actual total

 

     System.out.println("The sum from 1 to " + minNumber

             + " ... " + maxNumber + " is " + sum);

  }

}

·         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.

8.2      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.

// Name:

// Email:

 

import java.util.*;

 

public class Upper {

 

     public static void main(String[] args) {

    

           Scanner stdin = new Scanner(System.in);

          

           int numberUpperCase = 0;    // keeps track of the number of uppercase

                                                // characters that have been read

 

           // issue prompt for getting user to supply text

          

           System.out.println("Enter lines of text and the number of uppercase letters"

+ " will be counted");

 

           System.out.println("To indicate end of text, enter Ctrl-Z \n");

          

           // loop while there are more lines to process

          

           while ( stdin.hasNext() ) {

                // there is another line, so get it

               

                String input = stdin.nextLine();   // keeps track of the input value

               

                // process the characters in the current input line

               

                int i = 0;  // index of character to be processed next

               

                // nested loop iterates while there are more characters to process

                // in current input line

               

                while ( i < input.length() ) {

                     // process the ith character in the input line

                    

                     char currentCharacter = input.charAt(i);

                      

                     // test whether the character is uppercase

                     if ( Character.isUpperCase(currentCharacter) ) {

                           // got another uppercase character

                           ++numberUpperCase;

                     }

                    

                     // current character has been processed

                    

                     ++i;

                    

                     // ready to repeat the inner loop to process next character

                }

               

                // ready to repeat the outer loop to process the next line

 

           }

          

           System.out.println("Upper case chars: " + numberUpperCase);

     }

}

·         Open the program Upper.java.

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

·         Although the method stdin.read() reads a single character, its returns value is int. If the stream has un-extracted characters, the next available character is returned. However, if end of the stream has occurred, stdin.read()returns -1. For this reason, variable input is made an int.

·         The loop text expression compares the value of input with -1. If they do not match, then end of stream has not yet occurred and there is a character to process.

·         The body of the loop processes the character. The process begins with a conversion that casts the int representation of the input to a char representation. A char representation can be tested for uppercase-ness using Character class method isUpperCase(). Method isUpperCase() returns a boolean value that indicates whether its actual parameter is an uppercase letter.

·         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.

·         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. 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.

8.3      Using Input File Streams

Often programs examine data files. In this exercise, you will learn to use input file streams to extract data from a file. 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.

// Name:

// Email:

 

import java.io.*;

import java.util.*;

 

public class CharacterCounting {

 

   public static void main(String[] args){

 

      // determine the file name of interest

 

      Scanner stdin = new Scanner(System.in);

 

      System.out.print("Enter file name: ");

      String filename = stdin.next();

 

      // get a file stream representation ofthe file of interest

 

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

 

      // count the characters in the stream

 

      int numberCharacters = 0;   // keeps track of the number of characters

                                  // that have been read. there are none as

                                  // of yet

 

      // process the file stream line by line

 

      // loop while there is more text

 

      while ( filein.hasNext() ) {

         // there is more text so read the next line

 

         // *************** insert code here ******************

        

 

         // add the length of the line to the running total

 

         // *************** insert code here ******************

        

 

         // ready to repeat the loop

 

       }

 

      System.out.println("Number of characters in " + filename

          + ": " + numberCharacters);

   }

}

·         CharacterCounting.java first prompts its user for the name of the file and creates a Scanner file stream representation filein from the filename. The representation is a two-step process. First, a File representation is built using the name of the file of interest as its String parameter. Class File is the basic file naming library in Java and is part of java.io.. A Scanner representation filein then is created out of the File representation. With filein, a programmer has access to the accustomed input extraction methods (e.g., nextLine() and hasNext()).

·         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 processes the text from the file input stream.

·         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.

8.4      Finishing up

·         Copy any files you wish to keep to your own drive.

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