请帮助格式化我的输出。
我被要求“编写一个程序,显示所有闰年,每行十个,在二十一世纪(从2001年到2100年),只有一个空格分开”。
虽然我得到了正确的结果,但它不符合要求的格式。
提前致谢
public class Leapyear {
public static void main(String[] args) {
//declare variabls;
int year;
int count=1;
int yearsperline = 10;
//loop
for(year=2001;2001<=2100;year++){
if((year%4==0 && year%100!=0) || (year%400==0))
System.out.print(year+",");
if ( year ==2100)
break;
while (count%10==0)
System.out.println();
}
}
}
答案 0 :(得分:0)
你可以这样写:
//declare variables;
final int YEARS_PER_LINE = 10;
final int START_YEAR = 2001;
//loop
for(int year = START_YEAR; year <= 2100; year++){
System.out.print(year);
if((year - START_YEAR) % YEARS_PER_LINE == (YEARS_PER_LINE - 1)) {
System.out.println();
} else {
System.out.print(",");
}
}
答案 1 :(得分:0)
试试这个:
public class LeapYear
{
public static void main(String[] args)
{
// declare variables
final int startYear = 2001;
final int endYear = 2100;
final int yearsPerLine = 10;
// loop
for (int year = startYear, count = 0; year <= endYear; year++)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
if (count % yearsPerLine != 0)
System.out.print(" ");
else if (count > 0 && count % yearsPerLine == 0)
System.out.println();
System.out.print(year);
++count;
}
}
}
}
答案 2 :(得分:0)
int startFromYear = 2001;
int stopAtYear = 2100;
int count = 0;
for(int i = startFromYear; i <= stopAtYear; i++){
if((i % 4 == 0 && i % 100 != 0)||(i % 400 == 0)){
System.out.print(i + " ");
count++;
if(count % 10 ==0)
System.out.println();
}
}
答案 3 :(得分:0)
100%正确!而且容易理解。
public class LeapYears
{
public static void main(String[] args)
{
int count = 0;
for(int i = 2001; i <= 2100; i++)
{
if ((i % 4 == 0 && i % 100 != 0)||(i % 400 == 0))
{
count++;
//if count is 10 then start a new line.
if(count % 10 == 0)
{
System.out.println(i);
}
//if count is smaller 10 then in the same line
else
{
System.out.print(i + " ");
}
}
}
}
}