Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use String.format() in Java to replicate tab "\t"?

I'm printing data line by line and want it to be organized like a table.

I initially used firstName + ", " + lastName + "\t" + phoneNumber.

But for some of the larger names, the phone number gets pushed out of alignment

I'm trying to use String.format() to achieve this effect. Can anyone tell me the format syntax to use?

I tried String.format("%s, %s, %20s", firstName, lastName, phoneNumber), but that's not what I want. I want it to look like this:

John, Smith            123456789

Bob, Madison         123456789

Charles, Richards  123456789

Edit: These answers seem to work for System.out.println(). But I need it to work for a JTextArea. I'm using textArea.setText()

Worked it out. JTextArea doesn't use monospaced fonts by default. I used setFont() to change that, and now it works like a charm. Thank you all for the solutions.

like image 741
ask Avatar asked Dec 09 '12 16:12

ask


1 Answers

consider using a negative number for your length specifier: %-20s. For example:

   public static void main(String[] args) {
     String[] firstNames = {"Pete", "Jon", "Fred"};
     String[] lastNames = {"Klein", "Jones", "Flinstone"};
     String phoneNumber = "555-123-4567";

      for (int i = 0; i < firstNames.length; i++) {
        String foo = String.format("%-20s %s", lastNames[i] + ", " + 
             firstNames[i], phoneNumber);
        System.out.println(foo);
      }   
   }

returns

Klein, Pete          555-123-4567
Jones, Jon           555-123-4567
Flinstone, Fred      555-123-4567
like image 192
Hovercraft Full Of Eels Avatar answered Nov 15 '22 18:11

Hovercraft Full Of Eels