我要做的是创建一个闰年计算器,它不仅可计算一年,而且可计算用户可输入的多年。现在,我只计算一年。
这是输出应该是什么样的:
该程序测试给定年份是否为闰年。
输入起始年份:2008
输入结束年份:2013
2008年是闰年
2012年是闰年
非常感谢您的回复!帮助我学到的东西远远超过我的讲师实际教授的内容:)
import java.util.Scanner;
public class LeapYears
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println ("This program tests whether a given " + "year is a leap year.");
System.out.print ("Type the starting year: ");
int year = keyboard.nextInt ();
System.out.print ("Type the ending year: ");
int EndYear = keyboard.nextInt ();
if (((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.");
}
}
答案 0 :(得分:0)
您可以简单地将闰年评估代码包装在方法中,并在循环中调用它,例如:
public boolean isLeapYear(int year){
if (((year%4 == 0) && (year%100 != 0)) || (year%400 == 0))
return true;
else
return false;
}
并在您的主要方法中:
System.out.print("Type the starting year: ");
int startYear = keyboard.nextInt();
System.out.print("Type the ending year: ");
int endYear = keyboard.nextInt();
for(int currentYear=startYear;currentYear++;currentYear<=endYear){
if(isLeapYear(currentYear))
System.out.println(currentYear + " is a leap year.");
else
System.out.println(currentYear + " is not a leap year.");
}
除此之外,最好为案例添加一些防御性代码,例如用户输入不是整数,startYear大于endYear。
答案 1 :(得分:0)
试试这个
GregorianCalendar gc = new GregorianCalendar();
for(int y = year; y <= endYear; y++) {
if (gc.isLeapYear(y)) {
System.out.println(y + " is leap year");
} else {
System.out.println(y + " is not leap year");
}
}
答案 2 :(得分:0)
使用while循环进行多年检查,但是一旦获得第一个闰年,下一次迭代将增加4年(即年=年+4; )。这样就可以避免不必要的检查。
Scanner keyboard = new Scanner(System.in);
System.out.println("This program tests whether a given "
+ "year is a leap year.");
System.out.print("Type the starting year: ");
int year = keyboard.nextInt();
System.out.print("Type the ending year: ");
int EndYear = keyboard.nextInt();
while (year <= EndYear) {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
year = year + 4;
} else {
//System.out.println(year + " is not a leap year.");
year++;
}
}
答案 3 :(得分:0)
是的,这是一个循环问题。尝试while循环:
import java.util.Scanner;
public class LeapYear {
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println ("This program tests whether a given " + "year is a leap year.");
System.out.print ("Type the starting year: ");
int year = keyboard.nextInt ();
System.out.print ("Type the ending year: ");
int EndYear = keyboard.nextInt ();
int temp=year;
while(temp<EndYear)
{ if (((temp%4 == 0) && (temp%100 != 0)) || (temp%400 == 0)) {
System.out.println (temp + " is a leap year.");
}
else
{
System.out.println (temp + " is not a leap year.");
}
temp++;
}
}
}