gpt4 book ai didi

java - 距离生日的天数计算不正确 (Java)

转载 作者:行者123 更新时间:2023-12-01 17:00:33 26 4
gpt4 key购买 nike

我正在开发这个java程序,它告诉用户他们的出生月份的天数和距离他们的生日还有多少天,前一部分有效,如果距离生日不到三个月,则距离他们的生日还有多少天。但我不明白为什么它在那之后不起作用

import java.util.*;
public class Jack_Dennin_HW2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("What month of the year is it?(1-12)");
int month = (sc.nextInt()-1);
System.out.println("What day of the month?");
int day = sc.nextInt();
System.out.println("What month is your birthday?(1-12)");
int bmonth = (sc.nextInt()-1);
System.out.println("What day of that month is your birthday?");
int bday = sc.nextInt();
Date today = new Date(month, day);
Date birthday = new Date(bmonth, bday);
int sum = (today.daysInMonth()-day+bday);
System.out.println("There are "+birthday.daysInMonth()+" days in your birth month");
if (month==bmonth)
{
if(day==bday)
{
System.out.println("Happy Birthday!");
}
else if(bday>day)
{
System.out.println("Your birthday is "+(bday-day)+" days away");
}
else
{
System.out.println("Your birthday is "+(365+bday-day)+" days away");
}
}
else
{

for(int i = month+1; i==(bmonth-1)%12; i++)
{
Date n = new Date(i%12,1);
sum=(sum+n.daysInMonth());
}
System.out.println("There are "+sum+" days until your birthday");
}
}
}
class Date
{
private int month;
private int day;
public Date(int month2, int day2)
{
month = month2;
day = day2;
}
public int getMonth()
{
return(month);
}
public int getDay()
{
return(day);
}
public String toString()
{
String day2;
if (day%10==day)
{
day2 = "0"+day;
}
else
{
day2 = day+"";
}
return(month+"/"+day2);
}
public int daysInMonth()
{
switch(month)
{
case 0: return(31);
case 1: return(28);
case 2: return(31);
case 3: return(30);
case 4: return(31);
case 5: return(30);
case 6: return(31);
case 7: return(31);
case 8: return(30);
case 9: return(31);
case 10: return(30);
case 11: return(31);
default: return(-1);
}
}
}

最佳答案

这是因为这一行:

for(int i = month+1; i==(bmonth-1)%12; i++)

具体来说,i==(bmonth-1)%12

我们取两个日期:1 月 1 日和 2 月 1 日。在这种情况下,month=0i=0+1=1i==1%12 为 true,并且您会进入for 语句并正确计算天数。

我们再选择两个日期:1 月 1 日和 4 月 1 日。在这种情况下,month=0i=1,但 i==2%12 为 false,因此您不会陷入for 语句,因此不会计算出正确的总和。

由于这是作业,我不会告诉你解决方案,但需要修复的行是i==(bmonth-1)%12。这是一个非常简单的修复。

附注花一些时间学习如何使用调试器! :)

关于java - 距离生日的天数计算不正确 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61511408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com