How to center a string using String.format?

后端 未结 9 1592
陌清茗
陌清茗 2020-11-30 12:28
public class Divers {
  public static void main(String args[]){

     String format = \"|%1$-10s|%2$-10s|%3$-20s|\\n\";
     System.out.format(format, \"FirstName\",         


        
9条回答
  •  暖寄归人
    2020-11-30 13:04

    Here's an example of how I've handled centering column headers in Java:

    public class Test {
        public static void main(String[] args) {
            String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
                    "October", "November", "December" };
    
            // Find length of longest months value.
            int maxLengthMonth = 0;
            boolean firstValue = true;
            for (String month : months) {
                maxLengthMonth = (firstValue) ? month.length() : Math.max(maxLengthMonth, month.length());
                firstValue = false;
            }
    
            // Display months in column header row
            for (String month : months) {
                StringBuilder columnHeader = new StringBuilder(month);
                // Add space to front or back of columnHeader
                boolean addAtEnd = true;
                while (columnHeader.length() < maxLengthMonth) {
                    if (addAtEnd) {
                        columnHeader.append(" ");
                        addAtEnd = false;
                    } else {
                        columnHeader.insert(0, " ");
                        addAtEnd = true;
                    }
                }
                // Display column header with two extra leading spaces for each
                // column
                String format = "  %" + Integer.toString(maxLengthMonth) + "s";
                System.out.printf(format, columnHeader);
            }
            System.out.println();
    
            // Display 10 rows of random numbers
            for (int i = 0; i < 10; i++) {
                for (String month : months) {
                    double randomValue = Math.random() * 999999;
                    String format = "  %" + Integer.toString(maxLengthMonth) + ".2f";
                    System.out.printf(format, randomValue);
                }
                System.out.println();
            }
        }
    }
    

提交回复
热议问题