在Java中使用Switch根据年龄组生成随机出生日期
我正在学习Java,对它的理解已经到了极限。我觉得我离那里不远,但不能完全到达那里。我需要做的是,生成一个随机的出生日期,并将其传递到一个变量中,这样我就可以在另一个类中使用它
然而,我还需要根据4个不同的年龄组改变年份
我的独立类生成DOB并传递到变量中,如下所示。有人能帮我整理一下并提出问题吗
package domainentities;
导入java。util。格雷戈里安卡伦达
BirthGenerator的公共类{
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));
}
}
# 1 楼答案
您的代码有一些问题
这是一个私有methode,它将返回methode参数,因此它什么也不做。您应该更改GeneratorDomainOfBirth的返回类型并返回创建的日期字符串:
此外,您没有设置月份(仅设置日期和年份)。你在哪里调用RandomDate类,有什么问题
# 2 楼答案
代码似乎还可以,但是我建议您将数据放入
enum
并避免switch
:看起来更简单,不是吗
顺便说一句,如果你要从练习开始思考设计。事实上,您的课程仅适用于2014年。需要在2015年进行修改。因此,您可能应该存储
minAge
和maxAge
而不是年份