User Interaction
The example use of the do was
a counting loop,
but this was only to show how it worked.
A better application is where
the user is repeatedly asked if the program
should continue:
import java.io.* ;
class SqrtCalc
{
public static void main( String[] args )
throws IOException
{
String chars;
double x;
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in) );
do
{
System.out.print("Enter a number-->");
chars = stdin.readLine();
x = (Double.valueOf(chars)).doubleValue();
System.out.println("Square root of" + x +
" is " + Math.sqrt( x ) );
System.out.print("Do you wish to continue? (yes or no) -->");
chars = stdin.readLine();
}
while ( chars.equals( "yes" ) );
}
}
|
It is slighly awkward to use a while loop for
this because you ask if the user wants to continue before
the program has done anything.
|