Difference between revisions of "Print a Calendar"

From CompSciWiki
Jump to: navigation, search
Line 58: Line 58:
 
if (dayOutput < 10)
 
if (dayOutput < 10)
 
{
 
{
strOutput += " " +dayOutput;     // Show that day with prepended space
+
strOutput += " " +dayOutput; // Show that day with prepended space
 
}
 
}
 
else
 
else
Line 64: Line 64:
 
strOutput += dayOutput;
 
strOutput += dayOutput;
 
}
 
}
strOutput += " "; // Space between numbers
+
strOutput += " "; // Space between numbers
 
}
 
}
 
else
 
else

Revision as of 12:10, 6 April 2010

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)

 

float
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

Solution

The solution...

Code

SolutionCode goes here. Please DO NOT put your code in <pre> tags!

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 JavaProggy
{
	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)
					{
						strOutput += " " +dayOutput;	// Show that day with prepended space
					}
					else
					{
						strOutput += dayOutput;
					}
					strOutput += " ";			// Space between numbers
				}
				else
				{
					strOutput += "   ";           	        // Output a blank cell
				}
			}

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

		return strOutput;
	}
}