1

I'm attempting to get spaces at the beginning of every other line of the output of this program:

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(" ");
        }
    }
}

The output of this program, if the user enters "4" for example, is:

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

I'm trying to get it to look like this:

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

1 Answer 1

8

Print the extra space only for even values of 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(" ");
    }
}

To be more explicit, the % operator (modulus) will return the remainder of a division operation. So any even number modulu 2 will return 0. Otherwise it would return 1. 13 % 10 == 3 because 13 / 10 = 1 remainder of 3.

2
  • Tried this but it still gave me a different output. Was the same except it combined the 2nd and 3rd line of A's into the same line.
    – Dingles
    Oct 20, 2013 at 22:31
  • @PatrickR. sorry, you're right. I edited my answer for clarity, and replaced a println with a normal print.
    – dckuehn
    Oct 21, 2013 at 13:35

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.