0

By the given task, the numbers can be 000, 001, 002 and so on. How can I save this number format?

int i = 000;
i++; 
System.out.println(i);  //the output is 1 but I want 001

So how can I have the value of i like 001?

veben
  • 8,680
  • 11
  • 48
  • 57
rozerro
  • 2,316
  • 2
  • 18
  • 38
  • 3
    `i = 000` is the same as `i = 0`. If you want to change how it outputs you can use `System.out.printf` – dangee1705 Jan 17 '19 at 19:35
  • 2
    There is no **number** 001. Only the number 1, and maybe the *literal* 01 (which indicates octal). 001 only makes sense a **string**. – GhostCat Jan 17 '19 at 19:36
  • You can format it. `String.format()` would work, you could also store it as a string (though that might not be very useful). If you just need the format, String.format would work perfectly for only when you need it to be formatted. – Frontear Jan 17 '19 at 19:38

3 Answers3

0

Store the original value in a String.

Try this: String originalValue = "000";

DwB
  • 33,855
  • 10
  • 50
  • 78
  • 1
    This might not fully align with OP's intention. For one, why bother storing a number in a string at all? OP wants to be able to manipulate the data as a number, while being able to format it to have beginning 0's. In that case, wouldn't `String.format` be a better approach? – Frontear Jan 17 '19 at 19:39
0

To display you int with a length of 3 digits, you can use String.format like this:

System.out.println(String.format("%03d", i));
veben
  • 8,680
  • 11
  • 48
  • 57
-1

The language-independent name for what it sounds like you're trying to do is "format". A lot of languages with C heritage will have a function named something like printf, fprintf, or sprintf, with a common protocol of % markers for their arguments.

This looks like the Java version.

ShapeOfMatter
  • 668
  • 4
  • 21