Java - 用printf动态填充左边

时间:2013-10-12 22:27:30

标签: java printf

我正在学习Java并且在这个愚蠢的小问题上花了太多时间。我正在尝试使用空格动态填充字符串输出的左侧,因此显示的所有值都将向左填充。问题是,在用户输入值之前,我不知道值的长度。

这是我正在尝试做的一个例子。 nLongestString是我显示的最长字符串的长度,strValue是字符串本身的值。这根本不起作用。如果我对nLongestString的值进行硬编码就可以了,但我不能这样做,因为我并不总是知道这些字符串会有多长。

 System.out.printf("%"+nLongestString+"s", strValue + ": ");

输出应如下所示:

thisisalongstring:
       longstring:
            short:

2 个答案:

答案 0 :(得分:1)

我没有看到你的问题,以下对我来说很好。 (Java 7)

修改:您是否检查了nLongestString的值?我猜它没有按照你的想法设定。

    String[] arr = { "foo", "bar", "foobar" };

    int max = 0;

    for( String s : arr ) {
        if( s.length() > max ) {
            max = s.length();
        }
    }

    for( String s : arr ) {
        System.out.printf(  ">%" + max + "s<%n", s );
    }

    Random random = new Random( System.currentTimeMillis() );
    // just to settle the question of whether it works when 
    // Java can't know ahead of time what the value will be
    max = random.nextInt( 10 ) + 6;

    for( String s : arr ) {
        System.out.printf(  ">%" + max + "s<%n", s );
    }
}

输出:

>   foo<
>   bar<
>foobar<
// the following varies, of course
>     foo<
>     bar<
>  foobar<

答案 1 :(得分:0)

如果您已有数据,那么您只需找到单词的最大长度,然后打印出来。这是代码示例

// lets say you have your data in List of strings
List<String> words = new ArrayList<>();
words.add("thisisalongstring");
words.add("longstring");
words.add("short");

// lets find max length
int nLongestString = -1;
for (String s : words)
    if (s.length() > nLongestString)
        nLongestString = s.length();

String format = "%"+nLongestString+"s:\n";// notice that I added `:` in format so 
                                        // you don't have to concatenate it in 
                                        // printf argument

//now lets print your data
for (String s:words)
    System.out.printf(format,s);

输出:

thisisalongstring:
       longstring:
            short:
相关问题