0

This is a program to read an integer:

public static void main(String argv[]) {
    Scanner input = new Scanner(System.in);
    int x = input.nextInt();
    System.out.println(x);
}

But if I enter an input like this: 000114 it will be read like 114.How to read integer starts with zeroes?

7
  • 2
    there is not integer with zero before the number it must be String, but you can convert it to integer Oct 30, 2015 at 20:17
  • 2
    Read it as a string, eg with input.next() or input.nextLine() and then you can convert it to an int with Integer.parse()
    – clcto
    Oct 30, 2015 at 20:17
  • 1
    Why do you need the leading zeroes? Perhaps the raw String is what you need.
    – gaborsch
    Oct 30, 2015 at 20:18
  • Possible duplicate of Converting String to Int in Java? Oct 30, 2015 at 20:19
  • @maytham-ɯɐɥıλɐɯ What the OP wants is to preserve the leading 0's, not only convert a String to an int. I believe this is not a dupe of the question you have linked.
    – Laf
    Oct 30, 2015 at 20:21

3 Answers 3

6

Zeros are ignored at the start of an int. If you need the zeros to be displayed, store the number as a String instead. If you need to use it for calculations later, you can convert it to an int using Integer.parseInt(), so your code should look like this:

String x = input.next();
System.out.println(x);

//if you need x to be an int
int xInt = Integer.parseInt(x);

Keep in mind that, in this example, xInt will lose the zeros.

1
  • That was the best solution for my question. other solutions are also very useful and good solutions. thanks to all of you :) Oct 30, 2015 at 20:30
4

Perhaps you should read the input as a string and not as an integer if you really need to have the leading zeroes.

0
3

That is the expected outcome when reading an int with leading 0s because 000114 isn't an int when represented like that. If you need it to be 000114 then you should read it as a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.