Home > Enterprise >  How do you print X number of characters in X number of lines?
How do you print X number of characters in X number of lines?

Time:10-05

This is a question I got in an assignment of my Java class.

Q: Write a java program to print the following output using single System.out.print(“*”)

stars

I achieved above using a single printline command.

class Example{
   public static void main(String[] args) {
      String star = "*";
      for (int a=0; a<5; a  ) {
         System.out.println(star);
         star = star   " *";
      }
   }
}

But my proffesor wants to strictly follow the instructions in the question, hence can only use a single System.out.print(“*”). Thanks in advance.

CodePudding user response:

class Example{
   public static void main(String[] args) {
      for (int a=0; a<6; a  ) {
          for (int b=0; b<a; b  ) {
                    System.out.print("* ");
          }
          System.out.print("\n");
      }
   }
}

You can do this without using println but you have to use print("\n") instead to indicate line break.

CodePudding user response:

You can use the print method instead of println but you have somehow to add an escape sequence (\n). In case that you can't add the new line character at the same print, you can use one of the following examples:

Using 2 for loops:

for (int i = 1; i <= 5;   i) {
    for (int j = 1; j <= i;   j)
        System.out.print("* ");

    System.out.print("\n");
}

Using 1 for loop with the String#repeat as a helper:

for (int i = 1; i <= 5; i  ) {
    System.out.print("* ".repeat(i));
    System.out.print("\n");
}

And the last one, using IntStream with the repeat as above (which i don't recommend it)

IntStream.rangeClosed(1, 5).forEach(c -> {
    System.out.print("* ".repeat(c));
    System.out.print("\n");
});
  • Related