shommi20 shommi20 - 3 months ago 36
Java Question

Print cross pattern in Java

I've got this homework exercise that I'm stuck on.

Basically we have to print a cross pattern with 'X' character, but the middle bit has to be empty.

So, the program has to read an integer from the command line and after executing it it should output a cross pattern.

Something like this:


x
x
x
x x x x x x
x
x
x


Hopefully you can see it formatted properly above, basically I don't how to add that empty bit in the middle.

This is what I have so far:

public class Cross {

public static void main(String[] args) {
int num = 0;
for (int i = 0; i < args.length; i++)
{
num = Integer.parseInt(args[i]);
drawCross(num);
}
}


public static void drawCross(int num){

for(int i = 0; i < num; i++)
{
for(int j = 0; j < num; j++)
{

if((i == num / 2) || (j == num / 2))
System.out.print("X ");

else
System.out.print(" ");
System.out.print(" ");

}
System.out.println();
}

}
}




Now, this above works, but it prints a normal cross, without the gap in the middle. (Also, I'm guessing that there's a smarter way of doing this instead of using sysout)

The only other requirements that they gave us are that the 'x' should be printed 4n times and that the program must handle invalid inputs.

I would appreciate if you guys can give me a hand!
Cheers

Answer

Worked for me:

public static void drawCross(int num){
    for(int i = 0; i < num; i++) {
        for(int j = 0; j < num; j++){
            if((i == num / 2) || (j == num / 2)){
                if((i == (num-1) / 2) == (j == (num-1) / 2)){
                    System.out.print(" ");
                } else {
                    System.out.print("X");
                }
            } else { 
                System.out.print(" ");
            }
            System.out.print(" ");
        }
        System.out.println();
    }
}