Ron Levitzky Ron Levitzky - 5 months ago 11
Java Question

Need assistance with looping in java

Currently working on some extra problem sets and seem to be stuck with this one. I need to make the following output:

* *
* *
* * * * *
* *
* *


I've got the cross down but i'm having problems with the middle line and was hoping someone could help me figure it out. Heres my code so far (input is set to 5):

public static void drawPlusVersion3(int input){
if (input % 2 != 0) {
for(int c = 0; c < input; c++) {
for(int r = 0; r < input; r++) {
if((c == input / 2) || (r == input / 2))
System.out.print("*");
if ( c == r){
System.out.print("*");
}
else
System.out.print(" ");
System.out.print(" ");
}
System.out.println();
}
}
}


Current output:

* *
* *
* * ** * *
* *
* *


Thanks in advance!

Answer

How about this:

for (int i = 0; i < input; i++) {
    for (int j = 0; j < input; j++) {
        if (j == input / 2 || i == input / 2 || i + j == input - 1) {
            System.out.print("* ");
        } else {
            System.out.print("  ");
        }
    }
    System.out.println();
}