for循环中每隔一行开头的空格

时间:2013-10-16 23:20:53

标签: java loops for-loop

我正在尝试在此程序输出的每一行的开头获取空格:

import java.util.Scanner;
public class Checkerboard
{
    public static void main(String[] args)
    {
        int num;

        Scanner input = new Scanner(System.in);

        System.out.println ("What is the integer?");
        num = input.nextInt();

        for (int x = 0; x < num; x++)
        {
            for (int y = 0; y < num; y++)
            {
                System.out.print("A ");
             }
         System.out.println(" ");
        }
    }
}

如果用户输入“4”,则该程序的输出为:

A A A A A
A A A A A
A A A A A
A A A A A

我试图让它看起来像这样:

A A A A A
 A A A A A
A A A A A
 A A A A A

1 个答案:

答案 0 :(得分:7)

仅为x

的偶数值打印额外空间
for (int x = 0; x < num; x++)
{
    for (int y = 0; y < num; y++)
    {
         System.out.print("A ");
    }
    System.out.println("");
    if (x % 2 == 0){
         System.out.print(" ");
    }
}

更明确地说,%运算符(模数)将返回除法运算的余数。因此任何偶数模数2将返回0.否则它将返回1. 13%10 == 3因为13/10 = 1剩余3。