Debugging a Program in Development
In this lesson, we will develop a program to display a calendar and add statements to trace the program's execution to help us find a coding error.
We'll cover the following...
The calendar problem
Imagine a Java program that displays a complete calendar for any given year. We already saw how to find the day of the week for any given date and how to detect when a year is a leap year. In the
previous lesson, we learned how to use a switch statement to get the number of days in a given month. Using these basic ideas, we could begin the definition of a class of calendars.
A first-draft solution
The program given below shows such a class still in development. The plan is to focus on computing the number of days in a month by writing and testing the private method getDaysInMonth. The class has
temporary implementations, or stubs, for other methods in the class. A short main method in the class Driver tests the class for two different years, one of which is a leap year. Click the RUN button to see what happens.
Observe that the output is correct, except for month 2. February does not have 31 days, even in a leap year. Let’s look at what we have. The class begins with one data field, year, and a constructor that initializes it. The method display, which should display a complete calendar, produces only basic output for now. It can have a less tedious definition after we study the repetition statements in the next chapter. This method calls the private method displayMonth, which is a stub that in turn calls the private method getDaysInMonth. The latter method is the one we want to develop. Since getDaysInMonth calls the private method isLeapYear, writing a stub for isLeapYear would normally make sense. ...