In: Computer Science
Write a class in Java called 'RandDate' containing a method called 'getRandomDate()' that can be called without instantiating the class and returns a random Date between Jan 1, 2000 and Dec 31, 2010.
RandDate.java
import java.util.Random;
public class RandDate {
private static String getMonthInWords(int m)
{
String mon = "";
switch(m + 1)
{
case 1:
mon = "Jan";
break;
case 2:
mon = "Feb";
break;
case 3:
mon = "Mar";
break;
case 4:
mon = "Apr";
break;
case 5:
mon = "May";
break;
case 6:
mon = "Jun";
break;
case 7:
mon = "Jul";
break;
case 8:
mon = "Aug";
break;
case 9:
mon = "Sept";
break;
case 10:
mon = "Oct";
break;
case 11:
mon = "Nov";
break;
case 12:
mon = "Dec";
break;
}
return mon;
}
public static void getRandomDate()
{
int daysNotLeap[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31};
int daysLeap[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31};
int d, m, y;
// We need to generate 3 random numbers for day, month and
year
Random random = new Random(System.currentTimeMillis());
// 1. Random number between 2000 & 2010 for year
y = random.nextInt((2010 - 2000) + 1) + 2000;
// now we need to check whether the year generated is a leap year
or not
if(!isLeapYear(y))
{
// NOT A LEAP YEAR
// 2. generate random number between 0 and 11 for month (11,
because array index starts from zero)
m = random.nextInt((11 - 0) + 1) + 0;
// 3. generate random number between 1 and daysNotLeap[m]
d = random.nextInt((daysNotLeap[m] - 1) + 1) + 1;
}
else
{
// A LEAP YEAR
// 2. generate random number between 1 and 11 for month (11,
because array index starts from zero)
m = random.nextInt((11 - 0) + 1) + 0;
// 3. generate random number between 1 and daysLeap[m]
d = random.nextInt((daysLeap[m] - 1) + 1) + 1;
}
// finally display the date in the format: Jan 1, 2000
System.out.println("Date generated: " + getMonthInWords(m) + " " +
d + ", " + y);
}
private static boolean isLeapYear(int y)
{
boolean isLeap;
if(y % 4 == 0)
{
if(y % 100 == 0)
{
if(y % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else
isLeap = false;
return isLeap;
}
}
RandDateTest.java (Main class)
public class RandDateTest {
public static void main(String[] args) {
RandDate.getRandomDate();
}
}
********************************************************** SCREENSHOT ******************************************************
SAMPLE RUN 1 :
SAMPLE RUN 2 :
SAMPLE RUN 3 :