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?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Beginner Programmer
  • 155
  • 1
  • 4
  • 16
  • 2
    there is not integer with zero before the number it must be String, but you can convert it to integer – Maytham Fahmi Oct 30 '15 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 '15 at 20:17
  • 1
    Why do you need the leading zeroes? Perhaps the raw `String` is what you need. – gaborsch Oct 30 '15 at 20:18
  • Possible duplicate of [Converting String to Int in Java?](http://stackoverflow.com/questions/5585779/converting-string-to-int-in-java) – Maytham Fahmi Oct 30 '15 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 '15 at 20:21
  • Do you mean you want to read 0114 as an octal number, not a decimal? – Mike Harris Oct 30 '15 at 20:21
  • @maytham-ɯɐɥıλɐɯ I don't think it's a duplicate since OP is not asking how to convert an String to int. – Luiggi Mendoza Oct 30 '15 at 20:22

3 Answers3

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.

Bethany Louise
  • 646
  • 7
  • 13
4

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

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.

Andres de Lago
  • 111
  • 1
  • 9