How do I properly align using String.format in Java?

前端 未结 5 1382
梦谈多话
梦谈多话 2021-01-16 09:22

Let\'s say I have a couple variable and I want to format them so they\'re all aligned, but the variables are different lengths. For example:

String a = \"abc         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-16 10:06

    You can achieve it as below-

        String a = "abcdef";
        String b = "abcdefhijk";
        double price = 4.56;
    
        System.out.println(String.format("%-10s %-10.2f", a, price));
        System.out.println(String.format("%-10s %-10.2f", b, price));
    

    output:

       abcdef     4.56      
       abcdefhijk 4.56
    

提交回复
热议问题