/*****************************************************************
** TableOfSquareRoots - program to demonstrate functions
**
** Three functions are defined to assist in creating a
** nice-looking table.  They are
**
** formatInt    - format an integer into a string, padding to the
**                left with spaces to create a string of a given
**                length
** formatDouble - format a double into a string, with a specified
**                number of decimal places, padding to the left
**                with spaces to create a string of a given length
** trim         - trim a double to have a specified number of
**                decimal places
**
** The output from this program looks as follows:
**
**    ====================
**     x  Square Root of x
**    --- ----------------
**      0           0.0000
**     25           5.0000
**     50           7.0710
**     75           8.6602
**    100          10.0000
**    125          11.1803
**    150          12.2474
**    175          13.2287
**    200          14.1421
**    ====================
**
** (c) Scott MacKenzie, 2000                             
******************************************************************/
public class TableOfSquareRoots
{
   public static void main(String[] args)
   {
      System.out.print("====================\n"
                    +  " x  Square Root of x\n"
                    +  "--- ----------------\n");      

      for (int x = 0; x <= 200; x += 25)
      {
         String s1 = formatInt(x, 3);
         String s2 = formatDouble(Math.sqrt(x), 17, 4);
         System.out.println(s1 + s2);
      }
      System.out.println("====================\n");
   }

   // format integer 'i' as a string of length 'len' (pad left with spaces)
   public static String formatInt(int i, int len)
   {
      String s = "" + i;
      while (s.length() < len)
         s = " " + s;
      return s;
   }

   // format double 'd' as a string of length 'len' & 'dp' decimal places
   public static String formatDouble(double d, int len, int dp)
   {
      String fx = (dp <= 0) ? "" + Math.round(d) : "" + trim(d, dp);
      while (fx.substring(fx.indexOf(".") + 1, fx.length()).length() < dp)
         fx += "0";
      while (fx.length() < len)
         fx = " " + fx;
      return fx;
   }

   // trim double 'd' to have 'dp' decimal places
   public static double trim(double d, int dp)
   {
      double factor = Math.pow(10.0, dp);
      return (int)(d * factor) / factor;
   }
}

