且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java-在For循环中的十个值之后打印新行

更新时间:2023-12-03 17:40:58

这就是我要做的.只需添加一个int计数器变量,就可以在每次打印一年时将其递增.当它达到10的倍数时,只需打印新行.

This is what I would do. Simply add an int counter variable, increment it every time that you print out a year. When it reaches a multiple of 10, simply print a new line.

import java.util.Scanner;

public class LeapYears 
{

public static void main(String[] args) 
{
    int firstY, finalY, counter;
    counter = 0;
    Scanner kb = new Scanner(System.in);

    System.out.print("Enter start year: ");
    firstY = kb.nextInt();

    System.out.print("Enter end year: ");
    finalY = kb.nextInt();



    for(; firstY <= finalY; firstY++)

    {
        if ((firstY % 4) == 0)

        {
            if ((firstY % 100) == 0)

            {
                if ((firstY % 400) == 0 )

                {
                    System.out.print(firstY + ", ");
                    firstY++;
                    counter++;
                    if (counter % 10 == 0) System.out.println("");
                }
            }

            else
            {
                System.out.print(firstY + ", ");
            }

        }
    }

}
}