while Loop Version

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

See below.

while Loop Version

The first iteration of the loop body can be made to happen by initializing chars to "yes." This is slighly awkward.

import java.util.Scanner;
class SqrtCalc
{
  public static void main( String[] args )
  {
    String chars;
    double x;
    Scanner scan = new Scanner(System.in );

    chars = "yes" ;        // enable first iteration of the loop

    while ( chars.equals( "yes" ) )
    {
      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();
   }

  }
}

QUESTION 6:

Examine the code (again.) How would it be written with a for loop?