有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java使用printf动态填充左侧

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

下面是一个我想做的例子。nLongestString是我显示的最长字符串的长度,strValue是字符串本身的值。这完全不是动态的。如果我为nLongestString硬编码一个值,它会工作,但我不能这样做,因为我并不总是知道字符串的长度

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

输出应该如下所示:

thisisalongstring:
       longstring:
            short:

共 (2) 个答案

  1. # 1 楼答案

    若你们已经有你们的数据,那个么你们只需要找到你们的单词的最大长度,然后打印出来。下面是代码示例

    // 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:
    
  2. # 2 楼答案

    我看不出你的问题,下面这些对我来说很好。(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<