RU beehive logo ITEC dept promo banner
ITEC 120
2009spring
ibarland
nokie
jmdymacek

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs

lab03b
more Calendar

If you have not already checked of lab03a—using GregorianCalendar, you must finish that before continuing.


Today's task

Task: Write code which, using one of your GregorianCalendar objects, constructs at least two different Strings representing that date. You may choose any two of the example date formats below (or any other reasonable variant you prefer). I recommend using a 24-hour clock.

You'll want to look at the opening section of the documentation for GregorianCalendar (and, if you want more details on the methods/constants themselves, see the documentation for Calendar).


Further refinements

The following are all optional (and of varying levels of difficulty).

Advanced/optional: leading-zeroes, using method-call

The biggest problem with our code as written is that we don't have leading zeroes… which is bad if MINUTES is (say) 4, since we would build the String "11:4", rather than "11:04".

To do this properly, you need to use an if-else statement, which we haven't yet talked about. For now, you can either copy/paste the following method into your code (and ask your lab instructor how to call it), or you can look at how it works and try adapting the code to use in your own main.

    /** Convert an int into a String, adding a leading "0" if necessary
     *  to make the result at least two characters long.
     *  Bug: as written, negative numbers aren't handled correctly.
     * @param n The number to convert into a String.
     * @return the String representing n, possibly with a leading zero.
     */
    static String pad2( int n ) {
      String frontPad;
      if (n < 10) {
        frontPad = "0";
        }
      else {
        frontPad = "";
        }
      return frontPad + Integer.toString(n);
      }

Advanced/optional: am/pm using if-else

If you really want to use "a.m." or "p.m." in your answer, the proper code would use an if-else statement, which we haven't yet talked about:

  String myAmPmInfo;
  if (cal.get(Calendar.AM_PM) == Calendar.AM) {
    myAmPmInfo = "a.m.";
    }
  else {
    myAmPmInfo = "p.m.";
    }

And, naming the day-of-week...

Here is an idea for a true hack: code which works, but is not elegant:
If you are have a day-of-week as a number in 0..6, might you be able to convert it to a string by using charAt (or, substring) along with "SunMonTueWedThuFriSat"? (This is non-elegant because we are using a single String to store seven different pieces of information; we'll learn about lists and arrays later, which are the proper ways to store entire collections of data.)

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs


©2009, Ian Barland, Radford University
Last modified 2009.Feb.16 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme