Programs using Printf

Link to printf notes

MyPrintf.java I especially want you to do #3 below.

Write a program that does the following:

  1. Print 1/7 to five decimal places
    The output should be 0.14285. (Is it rounded up to 0.14286 as it should be?)
  2. Use printf to print the following:
    "The cow's name is Bessy, she is brown and weighs 1200 kg."
    • BUT you need to use these variables in the output string:
      String name = "Bessy";
      String colour = "brown";
      int weight = 1200;
    • Thus if you were using System.out.print() you would write:
      System.out.print("The cow's name is " + name + ", she is " + colour + " and weighs " + weight +" kg.");
    • Do this using printf()
       
  3. Print numbers so that they are always 8 characters wide (with vertical bars on each side):
    • use a console font (non-proportional spaced) or it won't work
    • Here I am printing the number 123
      e.g. begin like this:
      int xx = 123;
      System.out.println("| 12345678 |");
      System.out.println("| ======== |");
      System.out.printf("| %8d |%n", xx);
    • You need to make your program print the following USING PRINTF CORRECTLY (the first 3 lines are done by the code above):
      | 12345678 |
      | ======== |
      |      123 | space padded
      | 00000123 | zero padded
      |     +123 | sign always included
      | 123      | left aligned
      |    123.0 | 1 decimal place <--- HERE YOU HAVE TO MAKE THE NUMBER A DOUBLE FOR IT TO WORK.
      			 so use %f instead of %d, and instead of xx, use (double)xx
      
    • To make sure that it's correct, make just one change: change xx to a number with more or fewer digits
      e.g. int xx = 4422; or int xx = 9;.
      Don't change anything else in the program and all of the vertical bars should still line up.