How to use a printf command to print a string array horizonatally in Java

Viewed 30

I am trying to print:

 String[] provinces = 
      { 
         "Ontario", 
         "Quebec", 
         "Nova Scotia",
         "New Brunswick", 
         "Manitoba", 
         "British Columbia",
         "Prince Edward Island"         
      };

using the following command:

for (String spiceTraders: provinces) {
       System.out.println("              " + spiceTraders);
   }

Now, this prints my output as I want but how do I do it with printf, just the way println command prints it and that is print vertically.

This is the desired output:

          Ontario
          Quebec
          Nova Scotia
          New Brunswick
          Manitoba
          British Columbia
          Prince Edward Island
2 Answers

You can use printf using %n to get the linefeed and %s to pass the String

    for (String spiceTraders: provinces) {
           System.out.printf("              %s%n", spiceTraders);
    }

Try this:

System.out.printf("%s", "              " + String.join("\n              ", provinces) + "\n");
Related