A Personal Milestone
Well, I'm very excited. I called in Java...er...sick to work on Java today. Slow going, but I made progress. After spending a while reading, I went back to do the exercises from the chapters. I instantly recognized the first exercise: it was the one that basically made me decide a few months ago that, if I couldn't make the time to study every day, it wasn't worth going after. If only I'd known then what I know now...
So I struck out with my pencil and paper. Sometimes I am amazed how much clear thinking can be done with a piece of blank paper and a pencil rather than typing things out on screen. Here is the assignment:
Using the countDays()
method from the DayCounter
application, create an application that displays every date in a given year in a single list from January 1 to December 31.
The last time I worked on this exercise, I struggled with it for hours. Compiling what I thought would work again and again just to find that the code wouldn't compile each and every time. This time, after a little pencil work (just for the record, 5 lines of pseudocode and three lines of actual code), I took DayCounter
and fashioned it into a functioning application in about twenty minutes. The only compiler error I got was because I had left the ";" off the m++;
. I'm so excited! Here is the code; I used the countDays
method without altering it.class ExerciseOne {
public static void main(String[] arguments) {
int yearIn = 2004;
int m = 1;
int d = 0;
if (arguments.length > 0)
yearIn = Integer.parseInt(arguments[0]);
while (m < 13) {
d = countDays(m, yearIn);
for (int i = 1; i < d + 1; i++) {
System.out.println(m + "/" + i + "/" + yearIn);
}
m ++;
}
}
static int countDays(int month, int year) {
int count = -1;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
count = 31;
break;
case 4:
case 6:
case 9:
case 11:
count = 30;
break;
case 2:
if (year % 4 == 0)
count = 29;
else
count = 28;
if ((year % 100 == 0) & (year % 400 != 0))
count = 28;
}
return count;
}
}
Huzzah!
1 Comments:
That's great, congrats on conquering your arch-nemesis (as far as programs go).
So if you wanted to expand on that program, you could rewrite the countDays() method to use the Calendar class.
Post a Comment
<< Home