I am trying to print out the image below using a for
loop. I’m using for
loops and if
statements to create an ASCII star in Java.
My code:
public class asciistar { public static void main(String[] args) { final int X = 9; for (int R = 0; R < X; R++) { for (int V = 0; V < X; V++) { if (R == V || R + V == X - 1 || V == X / 2 || R == X / 2) { System.out.print("* "); } else { System.out.print(" "); } } } } }
Answer
Your code works! Just add the printing of a newline at the end of the outer loop:
public static void main(String[] args) { final int X = 9; for (int R = 0; R < X; R++) { for (int V = 0; V < X; V++) { if (R == V || R + V == X - 1 || V == X / 2 || R == X / 2) { System.out.print("* "); } else { System.out.print(" "); } } System.out.println(""); } }
Result:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *