No. A for
loop is the best choice
for a counting loop.
The example used the do
in
a counting loop.
This was to show how it worked.
Usually you would use a for
loop.
A more appropriate use of a do
is
in a loop that interacts with the user.
Notice the statement that flushes the rest of the input line.
This is necessary because nextDouble()
reads only the
characters that make up the number. The rest of the line remains
in the input stream and would be what nextLine()
reads
if they were not flushed.
import java.util.Scanner ; class SqrtCalc { public static void main( String[] args ) { String chars; double x; Scanner scan = new Scanner(System.in ); do { System.out.print("Enter a number-->"); x = scan.nextDouble(); chars = scan.nextLine(); // flush rest of the line System.out.println("Square root of " + x + " is " + Math.sqrt( x ) ); System.out.print("Do you wish to continue? (yes or no) --> "); chars = scan.nextLine(); } while ( chars.equals( "yes" ) ); } }
Examine the code. How would it be written with a
while
loop?