Reputation: 1843
I'm learning Java and am at the edge of my understanding with this. I feel I'm not far off, but can't quite get there. What I need to do is, generate a random date of birth and pass it into a variable so I can use it in another class.
However, I also need to change the year, based on 4 different age groups.
My standalone class to generate the DOB and pass into the variable is as follows. Can anyone help me over the top by tidying and suggesting what's wrong?:
package domainentities;
import java.util.GregorianCalendar;
public class RandomDateOfBirthGenerator {
private static String getDateOfBirth(String dateOfBirth) {
return dateOfBirth;
}
public static enum Mode {
SENIOR, ADULT, YOUTH, CHILD
}
public static void generateRandomDateOfBirth(Mode mode){
GregorianCalendar gc = new GregorianCalendar();
int year = 0;
String dateOfBirth;
switch(mode){
case SENIOR:
year = randBetween(1900, 1940);
break;
case ADULT:
year = randBetween(1941, 1995);
break;
case YOUTH:
year = randBetween(1995, 2002);
break;
case CHILD:
year = randBetween(2002, 2014);
break;
}
gc.set(gc.YEAR, year);
int dayOfYear = randBetween(1, gc.getActualMaximum(gc.DAY_OF_YEAR));
gc.set(gc.DAY_OF_YEAR, dayOfYear);
dateOfBirth = gc.get(gc.DAY_OF_MONTH) + "/" + gc.get(gc.MONTH) + "/" + gc.get(gc.YEAR);
}
public static int randBetween(int start, int end) {
return start + (int)Math.round(Math.random() * (end - start));
}
}
Upvotes: 1
Views: 1334
Reputation: 115328
The code seems OK, however I'd suggest you to put data into enum
and avoid switch
:
public static enum Mode {
SENIOR(1900, 1940), ADULT(1941, 1995), YOUTH(1995, 2002), CHILD(2002, 2014);
private final int from;
private final int to;
Mode(int from, int to) {
this.from = from;
this.to = to;
}
public int from() {return from;}
public int to() {return to;}
}
public static int generateRandomDateOfBirth(Mode mode){
return randBetween(mode.from(), mode.to());
}
Looks simpler, doesn't it?
BTW if you are going forward from your exercise think about design. Indeed your program is good for year 2014 only. It will require modifications on year 2015. So, probably you should store minAge
and maxAge
instead of years.
Upvotes: 3
Reputation: 1911
There are some problems with your code.
private static String getDateOfBirth(String dateOfBirth) {
return dateOfBirth;
}
This is a private methode, which will return the methode parameter, so it does nothing. You should change the return type of generateRandomDateOfBirth and return the created date-string:
public static String generateRandomDateOfBirth(Mode mode){
String dateOfBirth;
... //Create dateOfBirth
return dateOfBirth;
}
Also, you are not setting the Month (only day and year). Where are you calling the RandomDate class and what are the problems?
Upvotes: 2