这是我所拥有的:
Scanner input = new Scanner(System.in); System.out.print("Enter a year: "); int Year = input.nextInt(); System.out.print("Enter a month (first three letters with the first" + " letter uppercase): "); String Month = input.next(); String ThirtyOne = "Jan" + "Mar" + "May" + "Jul" + "Aug" + "Oct" + "Dec"; String DaysThirtyOne = ThirtyOne.substring(21) + "31"; String Thirty = "Apr" + "Jun" + "Sep" + "Nov"; String DaysThirty = Thirty.substring(12) + "30"; String TwentyEight = "Feb"; String DaysTwentyEight = TwentyEight.substring(3) + "28"; String DaysLeapYear = TwentyEight.substring(3) + "29"; boolean isLeapYear = ((Year % 4 == 0) && (Year % 100 != 0) && (Year % 400 == 0)); if (ThirtyOne.contains(Month)) { System.out.println(Month + " " + Year + " has " + DaysThirtyOne + " days in it."); } if (Thirty.contains(Month)) { System.out.println(Month + " " + Year + " has " + DaysThirty + " days in it."); } if(TwentyEight.contains(Month)) { System.out.println(Month + " " + Year + " has " + DaysTwentyEight + " days in it."); } if (isLeapYear) { System.out.println(Month + " " + Year + " has " + DaysLeapYear + " days in it."); }
我是编程新手,所以如果这段代码看起来不成熟,我不会感到惊讶。无论如何,我让用户输入了一年零一个月(前三个字母)。我为a年创建了一个布尔变量,该变量表示用户输入的任何年份都需要被4、100和400整除。然后,我创建了一个if语句来确定是否是is年,以打印出“ Feb(任何年份用户输入)中有DaysLeapYear。” 我认为我的算法有问题,因为如果我要取出TwentyEight的if语句并仅保留the年if语句,则计算机甚至都不会打印出如果是was年,则Feb将有多少天。再说一次,我认为我在算法上出错了,
首先,您的isLeapYear条件需要更改。
boolean isLeapYear = ((Year % 4 == 0) && (Year % 100 != 0) || (Year % 400 == 0));
接下来,您的if(TwentyEight.contains(Month))对此需要进行更改以考虑leap年。
if(TwentyEight.contains(Month) && !isLeapYear) { System.out.println(Month + " " + Year + " has " + DaysTwentyEight + " days in it."); }