Roman
Roman

Reputation: 73

How to format multiple string parameters in Java

I'm writing the following for a class assignment:

public class SportsBall {
  public static void printDivision (String divName, String heading1, String heading2) {
    System.out.printf("%-30s", divName + heading1 + heading2);
  }

  public static void main(String[] args) {
    printDivision("bla ", "blahhhh ", "Northwest");
  }
}

The problem I'm having is specifying the length of the strings divName, heading1, and heading2. "%-30s" formats one of them, on either end, but for the life of me, I can't get the formatting right to set a length for each one. I tried three sets of specifiers separated by commas but it just prints the additional specifiers. I know this is probably something really simple...

Upvotes: 3

Views: 11499

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

If you want to put the result in a String you can use :

String result = String.format("%-30s %-30s %-30s", divName, heading1, heading2);

Then you can print it or use it in another places

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361575

To get formatting on each of them you need to pass them separately to printf rather than combining them into one string with +.

System.out.printf("%-30s %-30s %-30s", divName, heading1, heading2);

Upvotes: 2

Related Questions