1

I'm working on a question in JAVA where I need to perform some operation, say addition or subtraction on a number which is in the below format:

0001

I want to consider the 0's also when I add it with a other number, like

0001 + 1 = 0002
0562 + 0001 = 0563

but when I'm trying to do the same, I'm not able to output the number with 0's in the front. I have tried taking the number as String but it's not working. Kindly help on how can i consider taking 0 also in the front of a number. My code:

    Scanner in = new Scanner(System.in); 
    String UserInput;
    String a;

        System.out.println("Enter number: ");
        a=in.next();
             if (a.length()==4 && a.matches(".*\\d+.*")) {
                  UserInput=a;
        }

        UserInput = String.valueOf(Integer.parseInt(UserInput) + 1); 
        System.out.println(s1);

The Result:

Input:

0001

Output:

2
Dev
  • 101
  • 1
  • 1
  • 12

1 Answers1

1

Use System.out.format(String format, Object... args) to format the resulting integer with four digits:

int updatedInt = Integer.parseInt(UserInput) + 1;
System.out.format("%04d%n", updatedInt);

See http://docs.oracle.com/javase/tutorial/java/data/numberformat.html.

M A
  • 71,713
  • 13
  • 134
  • 174
  • I have a query though, here we are printing the number, how can I store the number in the format and use it for other operation ? – Dev Feb 22 '15 at 10:58
  • I think the [duplicate](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) mentioned in the comments points to a solution for this. – M A Feb 22 '15 at 11:02