0

I'm making a program that tells the day of the week for any date in the past or future. In order to split the 4-digit year into the first 2 numbers for century and last 2 numbers for year in order for the formula to work right I used the following 2 lines of code: Int y = yANDc / 100; Int c = yANDc % 100;

The problem is when I display the final output. If they typed in a 4-digit year between "xx00" and "xx09", it chops off any preceding "0"s. So, if they entered "2009", the final output would be written as "209".

Any ideas on how to fix this and format it to where it doesn't drop preceding "0"s?

  • FWIW: Java Integers don't contain leading zeros .. ever. To generate a *string* with leading zeros, see [printf/format and 0-padded fixed width fields](https://stackoverflow.com/q/1803670/2864740) (also [here](https://stackoverflow.com/q/473282/2864740) and [here](https://stackoverflow.com/q/275711/2864740)). – user2864740 Sep 04 '18 at 01:05
  • Format details themselves can be found in the Formatter class (used by aforementioned printf/format methods) javadoc - https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html – user2864740 Sep 04 '18 at 01:11
  • I'm new to posting on this site, but thank you for the responses. I would upvote your answers, but I don't know how to yet. I was able to fix it by adding: (using my variables) String sOFy = String.format ("%02d", y); – Ryan Huffman Sep 04 '18 at 01:33
  • You may take the [tour] and read [ask]. Also [help] could be helpful. Cheers. – Zabuzard Sep 04 '18 at 01:39

1 Answers1

3

You need to format the number for display.

Something like:

int year = 9;
int century = 20;

DecimalFormat df = new DecimalFormat("00");
System.out.println( df.format(century) );
System.out.println( df.format(year) );
System.out.println( df.format(century) + df.format(year) );

Or you could use the String.format(...) method:

System.out.println( String.format("%02d%02d", century, year) );
camickr
  • 321,443
  • 19
  • 166
  • 288