[英]Java leap year code problems
import java.util.Scanner;
public class Hw2JamesVaughn {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
if((year < 1582) == (year % 4==0))
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
if((year > 1582) == (year % 100 != 0) || (year % 400 == 0))
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
}
}
這是作業。
(要確定特定年份是否為a年,請使用以下邏輯:
我的Java year年計划已經到此為止,但它不起作用! 我一直在為此工作,我不知道出什么問題了。
首先,此if((year < 1582) == (year % 4==0))
檢查布爾相等性。 我認為您想要一個if((year < 1582) && (year % 4==0))
但恐怕仍然無法解決您的邏輯。
我建議您先創建一個方法。 第一部分應測試year
是否小於1582。如果是,則返回4的倍數,則返回true。第二部分在Wikipedia上進行了很好的描述。 放在一起會得到類似的結果,
private static boolean isLeapYear(int year) {
if (year < 1582) {
return (year % 4 == 0);
}
/*
* Rest of algorithm from: http://en.wikipedia.org/wiki/Leap_year
*/
if (year % 4 != 0) {
/*
* if (year is not divisible by 4) then (it is a common year)
*/
return false;
} else if (year % 100 != 0) {
/*
* else if (year is not divisible by 100) then (it is a leap year)
*/
return true;
}
/*
* else if (year is not divisible by 400) then (it is a common year)
* else (it is a leap year)
*/
return (year % 400 == 0);
}
然后,您可以使用printf
輸出結果,
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
System.out.printf("%d %s leap year", year, isLeapYear(year) ? "is a"
: "is not a");
}
最后,您的原始代碼可以實現為-
if (year < 1582 && year % 4 == 0)
System.out.println(year + " is a leap year");
else if (year < 1582)
System.out.println(year + " is not a leap year");
else if (year >= 1582 && (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)))
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
除了算法之外,您還可以使用Java內置的Calendar API計算leap年。
static boolean isLeapYear(int year){
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
return calendar.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.