所以这就是我到目前为止所有类getDayInMonth
必须保持不变,我希望它计算它匹配的次数。你好吗?
public class Real {
public static void main(String[] args) {
int realmonth = 5;
int realday= 11;
int count = 0;
for(int iteration = 1; iteration <=100; iteration ++) {
Random Month = new Random();
int month = Month.nextInt(12) + 1;
if(realmonth == month) count++;
System.out.println("The correct birthday was found " + count + " times during the 100 iterations.");
}
public static int getDayInMonth(int month) {
final int JANUARY = 1; final int JULY = 7;
final int FEBRUARY = 2; final int AUGUST = 8;
final int MARCH = 3; final int SEPTEMBER = 9;
final int APRIL = 4; final int OCTOBER = 10;
final int MAY = 5; final int NOVEMBER = 11;
final int JUNE = 6; final int DECEMBER = 12;
Random dayGenerator = new Random();
switch (month) {
case JANUARY: case MARCH: case MAY: case JULY:
case AUGUST: case OCTOBER: case DECEMBER:
return dayGenerator.nextInt(31) + 1;
case APRIL: case JUNE: case SEPTEMBER: case NOVEMBER:
return dayGenerator.nextInt(30) + 1;
case FEBRUARY:
return dayGenerator.nextInt(28) + 1;
default:
return -1;
}
}
}
答案 0 :(得分:0)
for (int iteration = 1; iteration <= 10000; iteration++) {
Random Month = new Random();
int month = Month.nextInt(12) + 1;
// Added call to getDayInMonth
if (realmonth == month && getDayInMonth(month) == realday) {
count++;
}
}
// Moved this outside for loop
System.out.println("The correct birthday was found " + count + " times during the 100 iterations.");
为了简化您的代码,您可以随机选择一年中的某一天,即365,因为您似乎没有将闰年考虑在内
Random r = new Random();
int realDate = r.nextInt(365) + 1;
// Or assign one yourself with
// LocalDate.of(2013, 4, 31).getDayOfYear();
int count = 0;
for (int iteration = 1; iteration <= 10000; iteration++) {
int randDate = r.nextInt(365) + 1;
if (randDate == realDate) {
count++;
}
}
答案 1 :(得分:0)
你很亲密。问题是如何调用getDayInMonth
方法。这是一个方法,而不是您在问题中错误陈述的类。
此方法为static
,表示它独立于此类的实例。换句话说,不是面向对象的。所以我们用类名称来称呼它。
int dayOfMonth = Real.getDayOfMonth( month ) ;
扩展您的if
以测试month
和dayOfMonth
。
boolean monthMatch = ( month == realMonth ) ;
boolean dayOfMonthMatch = ( dayOfMonth == realDay ) ;
if ( monthMatch && dayOfMonthMatch ) { count++ ; }
请注意,按照惯例,Java程序员通常在if
语句中包含大括号,即使对于单行也是如此。
在Java中,实例以小写的第一个字母命名。因此,Random Month
应为Random month
。但是你已经有了这样一个变量名,所以把它变成Random monthRandom
。
另外,我会将其替换为:
int month = ThreadLocalRandom.current().nextInt( 1 , 13 ) ;
我们在那里使用13因为绑定是独占,所以12 + 1 = 13.请参阅class documentation。
顺便说一下,在实际工作而不是学校作业中,我们会使用java.time类来解决这个问题,例如Month
和MonthDay
。