Karol Cyrklaff Karol Cyrklaff - 1 year ago 47
Java Question

How do I add 0 to single digits in this java program?

I am very new to Java. I have barely gotten through the basics (this is my first attempt at using a while loop) and now conveniently have a problem at work that can clearly be solved with programming. We need to add numbers to a print document in the format "xx-xx-xx" such that it will begin with 00-00-00 and end with 99-99-99. Specifically, I need to have leading zeros for the single digits.

I have managed to write a program that prints the numbers we need and I just found out I can output to a text file simply in command prompt (horrifically slow on this old computer using Windows XP and java 1.7), but I can't figure out how to add 0 in front of single digit numbers.

Here's what I have:

public class Numbers {
public static void main(String[] args){
int a = 0;
int b = 0;
int c = 0;
while (a<100) {
c = c+1;
System.out.println(a + "-" + b + "-" + c);
else if(b<99) {
c = 0;
b = b+1;
System.out.println(a + "-" + b + "-" + c);
else if(a<99) {
c = 0;
b = 0;
a = a+1;
System.out.println(a + "-" + b + "-" + c);

I have tried a couple of things, but I am most likely not implementing them correctly because, again, I have no idea what I'm doing. I understand that there is a way to format strings in general and there is a printf function and I know there is something you can do with %02d (I've seen String.format("%02d", myNumber) as an answer, but couldn't figure out exactly how to implement that in my code) and I read something about PrintStream and PrintWriter, etc, but I am not nearly experienced enough to know how to use all of that.

The real problem is that I don't exactly have a lot of time to work on this, unfortunately our clients all demand quick turnaround times (they were already asking for a sample yesterday afternoon, hours after we got the job). I'm sure I would eventually be able to figure it out and I will continue trying when I have time, but I also have other work to do and didn't have time last night.

I was thinking of rewriting the code to get rid of the dashes (thinking maybe the fact that there is a string already being printed prevents me from being able to format what I print) but I expect I will run into other problems there.

I would greatly appreciate any input and suggestions for further exploration of java and programming in general (I think I love learning more than just about anything else, I am constantly ravenous and can't be sated).

Answer Source

You can do,

System.out.printf("%02d-%02d-%02d\n", a, b, c);

instead of your println statements.