Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format multiple string parameters in Java

Tags:

java

string

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...

like image 607
Roman Avatar asked Jan 19 '26 03:01

Roman


2 Answers

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

like image 171
YCF_L Avatar answered Jan 21 '26 16:01

YCF_L


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);
like image 32
John Kugelman Avatar answered Jan 21 '26 17:01

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!