Yes. Now the test part of the for will look for the sentinel.
In a sentinel controlled
loop the change part is often getting data from the user.
It would be awkward to do this inside a for.
So the change part is omitted from the for and put where it
is more convenient.
Here is an example.
The program keeps asking the user for a value for x.
Then it prints out the square root of x.
The user tells the program to end the loop by entering 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.valueOf( xChars ) ).doubleValue();
}
}
}
It probably would be preferable to use a while in this case.