./Birthday.java
import java.util.Random;
public class Birthday {
/** Between 1 and 12, inclusive; 1 = January, 2 = February, etc. */
private int month;
private int day;
// assumes February has 29 days
private static int[] daysInMonth = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
private static String[] months = {"January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November",
"December"};
private static Random random = new Random();
public Birthday(int month, int day) {
this.month = month;
this.day = day;
}
public Birthday() {
// Randomly generate the month: between 1 and 12, inclusive
month = random.nextInt(12) + 1;
// Picks a random day, based on the month
day = random.nextInt(daysInMonth[month-1]) + 1;
}
public int getMonth(){
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
/**
* @param month : 1 is January, 2 is February, ..., 12 is December
* @param day : must be in valid range for the month (typically 1 to 29-31)
* @throws IllegalArgumentException if month or day is out of the valid range
*/
public void setBirthday( int month, int day ) {
// check month (1 and 12) and day in range (depends on the month)
// if not, then throw an IllegalArgumentException
if( month < 1 || month > 12 ) {
throw new IllegalArgumentException("Month is not in valid range (1-12)");
}
if( day < 1 || day > daysInMonth[month-1] ) {
throw new IllegalArgumentException("Day is not in valid range (1-" + daysInMonth[month-1] + ")");
}
// set the values if valid
this.month = month;
this.day = day;
}
public String toString() {
return months[month-1] + " " + day;
}
public static void main(String args[]) {
System.out.println(new Birthday());
System.out.println(new Birthday());
Birthday b = new Birthday();
b.setBirthday(2, 30);
}
}
Generated by GNU enscript 1.6.4.