Introduction to Programming (CPSC 124)
—Hobart & William Smith Colleges, Fall 2014
Class Notes—October 20, 2014
Home | Syllabus | Calendar | Class Notes | Labs and Projects | General Notes |

Method Definitions and javadoc Documenation

Design Checklist

Code Example from Class

import java.util.Scanner; /** * Date formatting, using subroutines to organize the different tasks. */ public class DateFormatV2 { /** * Determines whether or not a date is valid. * * @param y the year (4 digit, y > 1582) * @param m the month (1 <= m <= 12, 1 = Jan, 2 = Feb, etc) * @param d the day of the month (1, 2, ...) * @return true if the specified date is valid, false if not */ public static boolean isValidDate ( int y, int m, int d ) { int[] maxDays = new int[]{31,28,31,30,31,30,31,31,30,31,30,31}; boolean leapYear = (y %4 == 0) && (y % 100 != 0 || y %400 == 0); if (leapYear) { maxDays[1] = 29; } boolean valid = (1 <= m && m <= 12); // valid month? valid = valid && (1 <= d); // Is d >= 1 ? valid = valid && (d <= maxDays[m-1]); // Is d no bigger than the max? return valid; } /** * Formats a date in the form: monthname day, year. If the date is invalid, * prints an error message instead. * * @param y the year (4 digit, y >= 1582) * @param m the month (1 <= m <= 12, 1 = Jan, 2 = Feb, etc) * @param d the day of the month (1, 2, ...) */ public static void formatDate ( int y, int m, int d ) { if (!isValidDate(y,m,d)) { System.out.println("Sorry. Invalid Date"); } else { // Now we'll print the formatted date (which we know is valid) String[] monthNames = new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; System.out.println(monthNames[m-1]+ " " + d + ", " + y); } } public static void main(String[] args) { // read and format dates until the user enters 'q' (or, really, any // non-integer) Scanner input = new Scanner(System.in); System.out.print("enter a date (yyyy mm dd) or q to quit: "); for ( ; input.hasNextInt() ; ) { int y = input.nextInt(); int m = input.nextInt(); int d = input.nextInt(); formatDate(y,m,d); System.out.print("enter a date (yyyy mm dd) or q to quit: "); } } // end of main() } // end of class DateFormatV2

John Lasseter