Difference between revisions of "Print a Calendar"
From CompSciWiki
Line 56: | Line 56: | ||
{ | { | ||
dayOutput = currentCell - firstDay + 1; // What day of the month to show | dayOutput = currentCell - firstDay + 1; // What day of the month to show | ||
− | if (dayOutput < 10) | + | if (dayOutput < 10) // If the number is under ten, we need |
− | { | + | { // to pad our number with a space |
− | strOutput += " " | + | strOutput += " "; |
} | } | ||
− | + | ||
− | + | strOutput += " " dayOutput; // Space between numbers | |
− | + | ||
− | + | ||
− | strOutput += " "; | + | |
} | } | ||
else | else |
Revision as of 12:18, 6 April 2010
Back to the Program-A-Day homepage
ProblemHow 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)
|
An image or By Students section | |
---|---|---|
SolutionThe solution... | ||
CodeSolutionCode goes here. Please DO NOT put your code in <pre> tags! |
// 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) // 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; } }