Results 1 to 2 of 2
  1. #1
    hill0093 is offline Member
    Join Date
    Mar 2013
    Posts
    20
    Rep Power
    0

    Default how do I get specified width of integer printed output

    If I code:
    int num0=0,num1=1,num999=999;
    System.out print(num0+","+num1);
    System.out println(","+num999);
    I believe I'll get: 0,1,999
    but I want 0000,0001,0999
    i.e. a width of 4 for small integers
    How do I do this?
    I cannot understand printf, for example,
    which is probably the way to do it.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,033
    Rep Power
    6

    Default Re: how do I get specified width of integer printed output

    The key to understanding printf is understanding format.

    Java Code:
    System.out.printf("%04d,%04d,%04d%n", num0,num1,num999);
    If you don't want the leading zeroes, change %04d to %4d.
    If you don't want the spaces, change %04d to %d.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 2
    Last Post: 09-13-2013, 08:35 PM
  2. Output printed in wrong order?
    By SamJava_the_Hut in forum New To Java
    Replies: 3
    Last Post: 08-27-2013, 11:39 PM
  3. Replies: 2
    Last Post: 10-26-2011, 09:52 PM
  4. How to Print every tenth integer in my output
    By jim01 in forum New To Java
    Replies: 13
    Last Post: 04-16-2011, 04:00 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
  •