Yes. Now the test part of the for
will look for the sentinel.
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.io.*; class evalSqrt { public static void main (String[] args ) throws IOException { BufferedReader userin = new BufferedReader(new InputStreamReader(System.in) ); String xChars; double x; System.out.println("Enter a value for x or -1 to exit:") ; xChars = userin.readLine() ; x = ( Double.valueOf( xChars ) ).doubleValue(); for ( ; x >= 0.0 ; ) { System.out.println( "Square root of " + x + " is " + Math.sqrt( x ) ); System.out.println("Enter a value for x or -1 to exit:") ; xChars = userin.readLine() ; x = Double.parseDouble( xChars ); } } }
This program would be better if a while
statement
were used in place of the for
statement.