我需要为我的班级制作一个程序,询问用户3年不同的年份并告诉他/她这个年份是否是闰年...这是我的代码(PS我们需要使用循环来做这样就保持循环):
import java.util.Scanner;
import java.util.*;
public class BetterLeapYear
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int year = s.nextInt();
if (year > 1582){
for (int i = 1; i <= 3; i++)
{
System.out.print ("Please enter a year: ");
year = s.nextInt();
}
if (((year%4)== 0) && ((year%100)==0) && ((year%400)==0)) {
System.out.print("That year was a leap year");
}
else if (((year%4)== 0) && ((year%100)==0) && ((year%400)!=0)){
System.out.println("This year was not a leap year");
}
else if ((year%4)== 0){
System.out.print("This year was a leap year");
}
else
System.out.print("This year was not a leap year");
}
else
System.out.print ("Please enter a year after 1582");
}
}
答案 0 :(得分:0)
您首先应该让用户输入年份值。然后检查是否在1582年之前。并最后检查是否是闰年。
将代码year = s.nextInt();
和if (year < 1582) {
放入for循环以接收输入的年份,并检查输入的年份是否在1582之后。
这三个步骤如下:
像
for (int i = 1; i <= 3; i++) {
/*
* Step#1 Receive a year value
*/
System.out.println("Please enter a year: ");
year = s.nextInt();
/*
* Step#2 Check if the year is after 1580 or not.
*
*/
if (year < 1582) {
System.out.println("Please enter a year after 1582");
} else {
/*
* Step#3 Check whether the year entered is leap year or not
*/
if (((year % 4) == 0) && ((year % 100) == 0)
&& ((year % 400) == 0)) {
System.out.println("That year was a leap year");
} else if (((year % 4) == 0) && ((year % 100) == 0)
&& ((year % 400) != 0)) {
System.out.println("This year was not a leap year");
} else if ((year % 4) == 0) {
System.out.println("This year was a leap year");
} else
System.out.println("This year was not a leap year");
}
}