Site Navigation

Site Search

Chapter 5: Loops and Files

Learning Objectives

After completion of this chapter, you should be able to

Use Increment and Decrement Operators

Java, and many other programming languages, use a short-cut notation to add or subtract one from a variable

It is recommended that ++ and -- be used as a stand-alone statement. Used in this manner, it does not matter whether the operator goes before (prefix) or after (postfix) the variable.

int number;
number = 5;

number++;
System.out.println(number);

number--;
System.out.println(number);
 

Explain the difference between Prefix and Postfix modes

When the increment or decrement operators are used in an expression:

number = 5;
System.out.println(number++);

Know the three type of loops used in Java programs

Loop statements allow us to execute a Java statement(s) multiple times repetitively. Like if statements, loops are controlled by Boolean expressions

Java has three kinds of loop statements:

  1. while loop
  2. do-while loop
  3. for loop

The programmer must choose the right kind of loop for the situation

Use while loops

The while statement has the following syntax:

   while ( boolean expression )
   {
      statement(s);
   }

while is a reserved word in Java.

Each time the loop body is executed, the condition is checked. If the loop condition is true, the loop continues to execute. If the loop condition is false, the loop terminates.

The loop body is executed repetitively until the condition becomes false. One single cycle of the loop is called an iteration.

Write a simple count-controlled while loop

   int count;
   count = 1;

   while (count <= 5)
   {
      System.out.println(count);
      count = count + 1;
   }

   System.out.println ("Done");
   

Prevent infinite loops

Use while loops for error checking user input

while loops are often used to check for valid user input, looping repetitively until the user gets it right!

   int number;  
   Scanner keyboard = new Scanner (System.in);
     
   System.out.print("Enter a number between 1 to 100: ");
   number = keyboard.nextInt();

// Validate the input
   while ((number < 1) || (number > 100))
   {
      System.out.println("That number is invalid.");
      System.out.print("Enter a number between 1 to 100: ");
      number = keyboard.nextInt();
   }

   System.out.println ("You entered " + number);
 

Use while loops for calculating a running total

while loops are often used to keep track of a running total

   int count;
   int runningTotal;
     
   count = 1;
   runningTotal = 0;
   while (count <= 6)
   {
      runningTotal = runningTotal + count;
      System.out.println(count);
      count = count + 1;
   }
 
   System.out.println ("Total = " + runningTotal);
 

Use sentinel values with running totals

Sometimes (usually) the end point of input data is not known. A sentinel value can be used to notify the program to stop acquiring input.

In the case of user input, the user could be prompted to enter a value that is not normally in the input data range (i.e. -1 where normal input would be positive.)

   // Declare and initialize local variables
      int numberOfScores = 0;
      double total = 0.0;
      double average = 0.0;
      int score;
     
      Scanner keyboard = new Scanner(System.in);

   // Get the first score
      System.out.print("Enter the score (-1 to stop): ");
      score = keyboard.nextInt();

   // Loop until the user enters the sentinel value of -1              
      while (score != -1)
      {
         total = total + score;
         numberOfScores++;

      // Get the next value
         System.out.print("Enter the score (-1 to stop): ");
         score = keyboard.nextInt();
      }

   // Calculate and print the average test score.
      average = total / numberOfScores;
      System.out.println("The average is " + average);
      System.out.println();
     

Use text files for input and output

Entering data from the keyboard could get tedious for the user. More often we use data files.

Write data to a text file

Two Java classes are used to write data to files:

Both classes are defined in the Java package io

import java.io.*;          // Needed for the file classes
   FileWriter fwriter = new FileWriter("StudentData.txt");
   PrintWriter outputFile = new PrintWriter(fwriter);

   outputFile.print("Hello ");
   outputFile.println("World");
   
   outputFile.close();

Throwing exceptions in your program

When something unexpected happens in a Java program, an exception is thrown. The method currently executing when the exception is thrown must either handle the exception or pass it up the line.

To pass it up the line, the method needs a throws clause in the method header.

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

Read data From a file

Java provides several classes to read data from a file.
   String filename;
   String inputLine;
   
   System.out.print("Enter the filename: ");
   filename = keyboard.nextLine();
   
   FileReader freader = new FileReader(filename);
   BufferedReader inputFile = new BufferedReader(freader);
   
   inputLine = inputFile.readLine();
   
   inputFile.close();

Example: Summing numbers in input file

   // Initialize the accumulator
      double sum = 0.0;

   // Read the first number
      String number = inputFile.readLine();

      while (number != null)
      {
         sum = sum + Double.parseDouble(number);
         number = inputFile.readLine();
      }

   // Close the file
      inputFile.close();
 
   // Display the sum
      System.out.println(sum);

Use do-while loops

The do-while loop is a post-test loop, which means it will execute the loop prior to testing the condition.

The do-while loop, more commonly called a do loop, takes the form:

   do
   {
      statement(s);
   } while ( boolean expression );

Example: TestAverage.java

   import java.util.Scanner;

    public class TestAverage
   {
       public static void main(String[] args)
      {
      // Declare local variables
         String userInput;
         double score1;
         double score2;
         double score3;  
         double average;
         
      // Create a Scanner object
         Scanner keyboard = new Scanner(System.in);
     
         do
         {
         // Get the three test scores.
            System.out.print("Enter three test scores: ");
            score1 = keyboard.nextDouble();
            score2 = keyboard.nextDouble();
            score3 = keyboard.nextDouble();

         // Skip over remaining newline
            userInput = keyboard.nextLine();
           
         // Calculate and print the average test score.
            average = (score1 + score2 + score3) / 3.0;
            System.out.println("The average is " + average);
            System.out.println();
         
         // Does the user want to average another set?
            System.out.print("Would you like to average "
                            + "another set of test scores (Y or N)? ");
         
            userInput = keyboard.nextLine().trim();
           
         } while (userInput.equalsIgnoreCase("Y"));
      }
   }

Use for loops

Java provides a third looping construct: the for statement.

The for statement has the following syntax:

   for ( initialization; boolean condition; increment )
   {
      statement(s);
   }

for statements are most often used with simple counting loops. For example, we could use a for statement to display the values 1 to 5 on the computer screen

      for (int count = 1; count <= 5; count++)
      {
         System.out.println(count);
      }
     
      System.out.println ("Done")

A for loop can easily be rewritten as while loop

Use a for loop to calculate a running total

Loops allow the program to keep running totals while evaluating data.

  // Declare and initialize local variables
      int numberOfScores = 0;
      double total = 0.0;
      int score;
           
  // Find out how many scores to average
      System.out.print("How many scores do you have to average? ");
      numberOfScores = keyboard.nextInt();
     
   // Get a running total of scores
      for (int count = 1; count <= numberOfScores; count++)
      {
         score = keyboard.nextInt();
         total = total + score;
      }
     
   // Calculate and print the average test score
      average = total / numberOfScores;
      System.out.println("The average is " + average);
      System.out.println();

Write nested loops in Java

Like if statements, loops can be nested. If a loop is nested, the inner loop will execute all of its iterations for each time the outer loop executes once.

   for(int i = 0; i < 10; i++)
   {
      for(int j = 0; j < 10; j++)
      {
         loop statements;
      }
   }

The loop statements in this example will execute 100 times.

Example of Nested Loops

   import java.text.DecimalFormat;

    public class Clock
   {
       public static void main(String[] args)
      {
         DecimalFormat fmt = new DecimalFormat("00");    
         
         for (int hours = 1; hours <= 12; hours++)
         {
            for (int minutes = 0; minutes <= 59; minutes++)
            {
               for (int seconds = 0; seconds <= 59; seconds++)
               {
                  System.out.print(fmt.format(hours) + ":");
                  System.out.print(fmt.format(minutes) + ":");
                  System.out.println(fmt.format(seconds));
               }
            }
         }
      }
   }

Use break and continue Statements

The break statement can be used to abnormally terminate a loop.

The use of the break statement in loops bypasses the normal mechanisms and makes the code hard to read and maintain. It is considered bad form to use the break statement in this manner.

The continue statement will cause the currently executing iteration of a loop to terminate and the next iteration will begin.

The continue statement will cause the evaluation of the condition in while and for loops. Like the break statement, the continue statement should be avoided because it makes the code hard to read and debug.

Deciding which loop to use