我想创建一个以日期为输入的 Java 程序 (27,2,2019) 并打印出它是哪一天。我只是假设只使用公历。参考是 1,1,1,这是星期一。我无法完成这个。有人可以帮帮我吗?我还计算了闰年。另外,在这个项目中,我不允许导入任何包,所以我应该正常进行。public class sortday{ public static void main (String [] args) { sortdayoftheyear(1,1,2019); } public static void sortdayoftheyear(int day, int month, int year) { final int [] months = {31,28,31,30,31,30,31,31,30,31,30,31}; { final int monthnum = 12; int totaldays=0; int newmon = month-1; //find which month it is int monthdays = months[newmon]; // find days of the month for (int i = 1; i < year; i++) { if (i%100 != 0 && i%4 == 0 && i%400 == 0) //check for leap year { totaldays = i*366; } else totaldays = i*365; } totaldays += (day) + (newmon*monthdays); if (totaldays%7 == 4) System.out.println("Sunday"); if (totaldays%7 == 5) System.out.println("Monday"); if (totaldays%7 == 6) System.out.println("Tuesday"); if (totaldays%7 == 0) System.out.println("Wednesday"); if (totaldays%7 == 1) System.out.println("Thursday"); if (totaldays%7 == 2) System.out.println("Friday"); if (totaldays%7 == 3) System.out.println("Saturday"); System.out.println("It had been " + totaldays + " since January 1,AD");} }}
1 回答
繁星coding
TA贡献1797条经验 获得超4个赞
您的代码中似乎存在不止一个错误。我发现:
每次通过您的
for循环时,您都会为totaldays. 这样只有最后一次通过循环才对结束有任何影响。我相信您打算每次迭代都做出贡献。正如 yole 在评论中所说,今年头几个月的
newmon*monthdays总天数是不正确的。newmon我什至认为 2 月 13 日你数的是 13 + 1 * 28,这是不对的。一个建议是你循环几个月并将它们的长度加起来。如果输入的年份是闰年,您总是在 2 月计算 28 天。有时你想数 29。确定一年是否为闰年的辅助方法会派上用场。
如果您的参考日期 1 月 1 日是星期一,我想您想在模运算最终得到 1 时打印
Thursday它。在这种情况下您正在打印。
我不知道是否还有更多。
没有功能性后果但您仍应解决的问题包括:
你没有使用常量
monthnum,所以删除它。从上面提到的常量到
System.out.println. 也删除那些。正确缩进,以便您和我可以阅读您的代码。
在编写代码供他人阅读(包括 Stack Overflow 用户)时,请遵守命名约定。打电话给班级
SortDay或FindDayOfWeek。方法sortDayOfTheYear或printDayOfWeek。
添加回答
举报
0/150
提交
取消
