我正在为学校开发一个程序,以获取用户输入的年份并检查它是否是闰年。它还应该检查年份是否早于 1582 年,如果是则返回错误。我遇到一个问题,如果用户输入 [1582, 1599] 之间的年份,程序将停止并且不打印任何内容。如果我将值更改为 1600,它不会返回 [1600, 1639] 之间的任何内容。不知道为什么会发生这种行为。任何帮助将不胜感激。
import java.util.Scanner;
public class Leapyear {
public static void main(String[] args) {
Scanner Jeff = new Scanner(System.in);
//System.out.print("Run Leapyear progra? Enter true or false: ");
//boolean RunLoop$ = Jeff.nextBoolean();
System.out.print("\nPlease enter a year: ");
int Year = Jeff.nextInt();
//while(RunLoop$ = true)
if (Year <= 1582)
System.out.println("The entered year is prior to the Gregorian Callandar");
else
if (Year % 4 == 0)
if (Year % 400 + Year % 100 == 0)
System.out.println("The entered year is a leapyear");
else
System.out.println("The Entered year is not a leapyear");
}
}
最佳答案
您的 if
语句不正确。我赞同 David 的评论,并强烈建议对每个 if
语句使用括号(这也在 - 尽管古老,但大多数仍然有效 - Code Conventions for the Java Programming Language 中推荐)。
此外,切换到合适的 IDE 和/或利用其源代码格式化支持将极大地帮助您解决此类问题。
简单(自动)清理会生成以下 if
语句片段,这在应用程序逻辑方面完全等效:
if (Year <= 1582) {
System.out.println("The entered year is prior to the Gregorian Callandar");
} else if ((Year % 4) == 0) {
if (((Year % 400) + (Year % 100)) == 0) {
System.out.println("The entered year is a leapyear");
} else {
System.out.println("The Entered year is not a leapyear");
}
} // else?
您现在可以清楚地看到,如果 Year
大于 1582 但不能被 4 整除,则不会有任何输出。
关于Java闰年检查程序。对边缘值无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42425976/