The Java Program: Squares.java

  1 import java.text.DecimalFormat;
  2 
  3 class Squares {
  4 
  5    // left justify a string by padding with blanks
  6    private final static String padding = "                                   ";
  7    public static String pad (String s, int width) {
  8       final int n = Math.max (width-s.length(), 0);
  9       return (s+padding.substring(0,n));
 10    }
 11    // right justify a string by padding with blanks
 12    public static String pad (int width, String s) {
 13       final int n = Math.max (width-s.length(), 0);
 14       return (padding.substring(0,n)+s);
 15    }
 16 
 17    // works with thousands and millions; rounds with BigDecimal.ROUND_HALF_UP
 18    // DecimalFormat uses half-even rounding (BigDecimal.ROUND_HALF_EVEN) for formatting.
 19    final static DecimalFormat df = new DecimalFormat ("#,##0");
 20    public static String fmt (int i, int width) {
 21       return (pad (width, df.format (i)));
 22    }
 23 
 24    final static DecimalFormat ff = new DecimalFormat ("#,##0.00");       
 25    public static String fmt (float f, int width) {
 26       return (pad (width, ff.format (f)));
 27    }
 28 
 29    public static void main (String[] args) {
 30       for (int i=0; i<=30; i++) {
 31          System.out.println (fmt(i,3)+fmt(i*i,5)+fmt(i*i*i,8));
 32       }
 33       System.out.println ();
 34 
 35       for (int i=2; i<13; i++) {
 36          System.out.print (fmt(i,2));
 37          for (int j=1; j<i; j++) {
 38             float f = (float)j / (float)i;
 39             System.out.print (fmt(f,6));
 40          }
 41          System.out.println ();
 42       }
 43    }
 44 }
 45