我在添加它时遇到了问题,这样我的程序就会打印出某一年中的天数。让我困惑的是闰年。不想报废。
我很困惑,正试图自己把它拼凑起来,应该寻求帮助。我想知道是否有办法修复它,或者我是否必须放弃它,重新开始。到目前为止,我的问题是指定日期。因为我不确定我是否应该把日子按月分开,只需要每年的总数,闰年也要这样做。
if (month == 1) {
month1 = "January";
daysInMonth = 31;
} else if (month == 2 ) {
month1 = "February";
daysInMonth = 28;
} else if (month == 3) {
month1 = "March";
daysInMonth = 31;
} else if (month == 4) {
month1 = "April";
daysInMonth = 30;
} else if (month == 5) {
month1 = "May";
daysInMonth = 31;
} else if (month == 6) {
month1 = "June";
daysInMonth = 30;
} else if (month == 7) {
month1 = "July";
daysInMonth = 31;
} else if (month == 8) {
month1 = "August";
daysInMonth = 30;
} else if (month == 9 ) {
month1 = "September";
daysInMonth = 30;
} else if (month == 10) {
month1 = "October";
daysInMonth = 31;
} else if (month == 11) {
month1 = "November";
daysInMonth = 30;
} else if (month == 12) {
month1 = "December";
daysInMonth = 31;
} else if (month >= 13 ) {
System.out.println("this date does not exist please try again");
}
if (month <= 12) {
System.out.println("this is the year you put in " + year);
System.out.println("this is the month you entered " + month1);
System.out.println("this is how many days are in that year " + daysInMonth);
}
}
如果使用java.time
,您将获得以下几个优势:
- 检查无效输入会更容易
- 你可以很容易地知道一年是否是闰年
- 您可以根据地区设置轻松打印月份名称甚至缩写,这意味着您可以切换语言和标准
下面是一个方法的小例子:
public static void printInformationAbout(int month, int year) {
// create an instance of month and year from the arguments
Year y = Year.of(year);
Month m = Month.of(month);
// collect information about the year
boolean isLeap = y.isLeap();
int days = y.length();
// and print that information
if (isLeap) {
System.out.println(year + " is a leap year and has " + days + " days");
} else {
System.out.println(year + " is a regular year and has " + days + " days");
}
// print month info (directly this time)
System.out.println(String.format("%s (month no. %d) has %d days in %d",
m.getDisplayName(TextStyle.FULL, Locale.ENGLISH),
m.getValue(), // number of the month
m.length(isLeap), // length of month in days
year));
}
如果你在main
中使用了这个,我们可以这样说:
public static void main(String[] args) {
printInformationAbout(5, 2020);
}
你会得到以下输出:
2020 is a leap year and has 366 days
May (month no. 5) has 31 days in 2020