Results 1 to 4 of 4
  1. #1
    chang123 is offline Member
    Join Date
    Feb 2017
    Posts
    1
    Rep Power
    0

    Default New to Java need some help

    Java Code:
    if (i <= MONTH_SIZES[j] && MONTH_SIZES[j] < 99)
    System.out.printf("%5s",  "0"+dayNum);
    i want to print out numbers to begin with a 0 for example those that are lower than 99 will be like this 001 002 003 and so on but after 100 it will just be 100 101 etcc not sure how to do that

  2. #2
    scarecrowkid is offline Member
    Join Date
    Dec 2016
    Posts
    20
    Rep Power
    0

    Default Re: New to Java need some help

    Here is one way to do it using ternary, which is just a condensed if-else statement

    Java Code:
           for(int i = 0 ; i < 250; i++) {
        	   System.out.printf((i<10) ? "00" : ""); //if i < 10 print out two zeros else print out nothing
        	   System.out.printf((i>9 && i<100) ? "0" : ""); //if i is between 10 and 99 inclusive, print out one zero else print out nothing
        	   System.out.printf("%d\n",i); //print out the number
           }

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: New to Java need some help

    That capability is build into the printf method. Just prefix 0 to the width designator to get leading zeros.

    Java Code:
     System.out.printf("%03d%n",1);
     System.out.printf("%03d%n",11);
     System.out.printf("%03d%n", 111);
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    agen4t7 is offline Member
    Join Date
    Feb 2017
    Location
    Chesapeake, VA
    Posts
    1
    Rep Power
    0

    Default Re: New to Java need some help

    Awesome. I was looking to do this the other day. Great timing on the post.

Posting Permissions

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