Home > Back-end >  How to use a printf command to print a string array horizonatally in Java
How to use a printf command to print a string array horizonatally in Java

Time:09-16

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

CodePudding user response:

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);
    }

CodePudding user response:

Try this:

System.out.printf("%s", "              "   String.join("\n              ", provinces)   "\n");
  •  Tags:  
  • java
  • Related