Results 1 to 3 of 3
  1. #1
    hamster is offline Member
    Join Date
    Apr 2012
    Posts
    14
    Rep Power
    0

    Default Using printf to pad spaces

    Hi there - i have just a quick question regarding printf

    I'm try to pad numbers into a certain size.

    eg if i had a number like 118

    It would look like this:
    System.out.printf("%6s", "118");

    Sure that puts 118 on the right side like this:
    'XXX118'

    But i want the statement to take in a variable pad size that will pad accordingly.
    eg. it could be 3, 8 or 7 for example.

    Could i use something like this: (btw the 8 is just a test value - 6 could be any number)

    System.out.printf("%*s", "118", 8);

    Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '*'

    Unfortunately the compiler doesnt like this. In a previous post i found that i had openJDK now i am using Oracle's own jdk

    I can't see why "%*s" doesnt take the 8 in for *. I read from an old post that "%*s" would work.
    The output with 8 would look like:
    'XXXXX118'

    X in place for blanks for the benefit of this post.

    Thanks,
    Hamster

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,539
    Blog Entries
    7
    Rep Power
    20

    Default Re: Using printf to pad spaces

    Read the API documentation for the Formatter class and you'll find that (sadly enough) you can't specify the width of a field with the '*' character; that's a C-ism; but nothing forbids you from constructing your own format String; e.g.

    Java Code:
    int width= ...;
    String format= "%"+width+"s";
    
    System.out.printf(format, "118");
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    hamster is offline Member
    Join Date
    Apr 2012
    Posts
    14
    Rep Power
    0

    Default Re: Using printf to pad spaces

    That's neat - thank you. I'll remember that for next time when the default doesnt have the option. :D

    Let me try that.

Similar Threads

  1. What are these values in printf
    By josho493 in forum New To Java
    Replies: 1
    Last Post: 04-19-2012, 05:47 AM
  2. printf VS printWriter.printf
    By Mapisto in forum New To Java
    Replies: 14
    Last Post: 01-20-2012, 12:29 PM
  3. Using printf without specifiers
    By FAkamo in forum New To Java
    Replies: 1
    Last Post: 10-17-2011, 08:46 AM
  4. printf
    By razzle in forum New To Java
    Replies: 4
    Last Post: 11-12-2010, 02:13 PM
  5. printf
    By Jack in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 04:31 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •