Print a Calendar

From CompSciWiki
Revision as of 10:13, 8 April 2010 by EdwinA (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

How do we use two loops to print out a calendar month?

We'll start this one easy. Make a function that takes two parameters: One that says what day of the week the first day of the month is, the other how many days are in the particular month. Your function prototype should look like

  function printMonth(int firstDay, int numDays)

 

By Students

I don't like Calendars. But I really like writing code! This question was a happy medium.

That said, nested loops are ideal for going over multiple groups of items. If your dealing with items in a grid, individual servers in multiple cities, or how many blueberries there are in everyone's ice cream cone, you'll need nested loops.

Solution

Now, you're probably going to hate my solution code to this. There's tonnes in there for output formatting that makes it convoluted and confusing. Those extras are not the point of this question. What I want from you is to have seven numbers drawn per line except the first and last weeks which might have less.

Code

Solution Code

Back to the Program-A-Day homepage


// Print a month starting on a friday with 31 days.
// Put this in a file called CalendarPrinter.java
import javax.swing.JOptionPane;

class CalendarPrinter
{
	public static void main(String args[])
	{
		String strOutput = printMonth(6, 31);

		System.out.println("January 2010:\n");
		System.out.println(strOutput);

		JOptionPane.showMessageDialog(null, strOutput);
	}

	static String printMonth(int firstDay, int numDays)
	{
		int currentCell = 0;    // What cell number are we in.
		int weekNum;            // What week number of the month
		int dayNum;             // What day of the week are we in

		int dayOutput = 0;      // What number to print in the cell

		String strOutput = "";	// Holds our final message

		for (weekNum = 0; weekNum < 6; weekNum++)
		{
			// Loop until we're at sunday OR we don't need to print more days
			for (dayNum = 0; dayNum < 7 && dayOutput + 1 <= numDays; dayNum++)
			{
				currentCell++;                                  // We're working on a new cell
				if (currentCell >= firstDay)                    // Can we start showing days yet?
				{
					dayOutput = currentCell - firstDay + 1; // What day of the month to show
					if (dayOutput < 10)			// If the number is under ten, we need
					{					// to pad our number with a space
						strOutput += " ";
					}

					strOutput += " " dayOutput;		// Space between numbers
				}
				else
				{
					strOutput += "   ";           	        // Output a blank cell
				}
			}

			strOutput += "\n";					// Done drawing a week, start a new line
		}

		return strOutput;
	}
}