The problem The date June 10th 1960 is special because when we write it in the following format, the month times the day equals the year:
Write a program that asks the user to enter a month (in numeric form), a day, and a two-digit year. The program should then determine whether the day times the month is equal to the year; if so, it should display a message indicating that the date is magic. Otherwise, it should display a message indicating that the date is not magic.
Breaking it down public static void main ( String [] args ) {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner ( System . in );
// Ask user for input
System . out . print ( "Enter date in mm/dd/yyyy format:" );
String dateAsString = keyboard . next ();
// close stream
keyboard . close ();
// Parse string to date
LocalDate date = LocalDate . parse ( dateAsString ,
DateTimeFormatter . ofPattern ( "MM/dd/yyyy" ));
// check date and display output
if ( magicDate ( date )) {
System . out . println ( "That date is magic!" );
} else {
System . out . println ( "Sorry, nothing magic about that date..." );
}
}
/**
* Method will check if a date is magic define by month * date = last two
* digets of year
*
* @param date
* @return true if the date is magic
*/
public static boolean magicDate ( LocalDate date ) {
int month = date . getMonth (). getValue ();
int day = date . getDayOfMonth ();
int year = date . getYear ();
String yearAsString = String . valueOf ( year );
String lastTwoDigits = "0" ;
if ( yearAsString . length () == 4 ) {
lastTwoDigits = yearAsString . substring ( 2 );
}
return ( month * day ) == Integer . parseInt ( lastTwoDigits );
}
Output Enter date in mm/dd/yyyy format:06/10/1960
That date is magic!
Unit tests @Test
public void test_magic_date () {
boolean magicDate = MagicDates . magicDate ( LocalDate . of ( 1960 , Month . JUNE ,
10 ));
assertTrue ( magicDate );
}
@Test
public void test_magic_not_date () {
boolean magicDate = MagicDates . magicDate ( LocalDate . of ( 1961 , Month . JUNE ,
11 ));
assertFalse ( magicDate );
}
Level Up Modify the unit to have mutliple dates using junit parameterized test Validate the date to be in correct MM/dd/yyyy format Magic dates posted by Justin Musgrove on 10 April 2014
Tagged: java and java-exercises-beginner
Share on: Facebook Google+