Deny int change 012345 to 5349

Possible duplicate:
Integer with leading zeros

The program that I am coding requires that I label the item with accession number 012345 and store it in the int variable.

This is a stripped down example of what I'm doing:

int test = 012345; System.out.println(test); 

it prints like:

 5349 

How do I print it as 012345, not 5349?

EDIT: I injected this into the constructor parameter for the custom class that I am initializing. Then I use the method to return the current number, then print it in the terminal window.

+4
source share
3 answers

You get the wrong number because when you add zero to an integer literal, Java interprets that number as an octal (i.e. base-8) constant. If you want to add a leading zero, use

 int test = 12345; System.out.println("0"+test); 

You can also use the generated output functionality using the %06d , for example:

 System.out.format("%06d", num); 

6 means use six digits; "0" means "pad with zeros, if necessary."

+9
source

As already mentioned, an int value with an initial zero is considered an octal value. If you don't need to have the test as an int, why not make it a string? how

 String test= new String("012345"); 

And if you want to use int for the test, you can not add 0, but just use a number and add 0 during printing.

In case you are interested in how you find how much initial zero should be added, you can do this as follows:

 int lengthOfItemID=6; int test=12345; String test1=new String("000000"+test); System.out.println(test1.substring(test1.length()-lengthOfItemID)); 

Pardon syntax errors were the years I last worked with java.

0
source

You can get the correct result using Integer.parseInt . This will make your string in decimal string. (found here ). The JAVA API here states that it takes a string and returns a decimal signature.

-1
source

Source: https://habr.com/ru/post/1445682/


All Articles