A while loop is useful if you are not certain how many times it should execute. For example, if a user is supposed to type in one number after another, and the loop stops when they type zero.
Remember that the boolean condition (after the while statement) tells whether the loop should continue, not when the loop should stop. So a while(..) loop is exactly like an if(..) command, but it is executed over and over again.
Trace this loop and predict what will be printed.
String name = "flexible";
int x =
0;
char letter = name.charAt(0);
while( letter != 'x' )
{ output( letter );
x = x + 1;
letter = name.charAt(x);
}
output( name.substring(x) );
loop ==> f , l , e .... stops when letter == 'x'
output(name.substring(x)) ==> "xible"