|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
If you have not already checked of lab03a—using GregorianCalendar, you must finish that before continuing.
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.
The following are all optional (and of varying levels of difficulty).
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); } |
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."; } |
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.)
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.Feb.16 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |