Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

syntax - How to use String.format() in Java to replicate tab " "?

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

I initially used firstName + ", " + lastName + "" + 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...