Sentinel Controlled Loop

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

Yes. Now the test part of the for will look for the sentinel.

Sentinel Controlled Loop

In a sentinel controlled loop the change part depends on data from the user. It is awkward to do this inside a for statement. So the change part is omitted from the for statement and put in a convenient location. Here is an example. The program keeps asking the user for x and printing the square root of x. The program ends when the user enters a negative number.

import java.util.Scanner;

class EvalSqrt
{
  public static void main (String[] args )
  {
    Scanner scan = new Scanner( System.in );
    double x;

    System.out.print("Enter a value for x or -1 to exit: ")  ;
    x = scan.nextDouble();

    for (    ; x >= 0.0 ;   )  
    {
      System.out.println( "Square root of " + x + " is " + Math.sqrt( x ) ); 

      System.out.print("Enter a value for x or -1 to exit: ")  ;
      x =  scan.nextDouble();
   }
  }
}

This program would be better if a while statement were used in place of the for statement.

QUESTION 13:

Do you think that the test part of a for can be omitted?