1

Why does my program ignore zeros when reading from a file? For example, here are the numbers from the file:

0001 0011 0010

Then this is my output:

1
11
10

This is my code:

    File file = new File("num.txt");
    Scanner scanner = new Scanner(file);
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            System.out.println(scanner.nextInt());
        } else {
            scanner.next();
        }
    }
Adil B
  • 9,911
  • 10
  • 41
  • 55
myadeniboy
  • 45
  • 7
  • 4
    That's because you are using hasNextInt(). Use like this instead: System.out.println(scanner.next()); – jhenrique Oct 09 '18 at 18:37
  • 5
    All numbers do that. You either need to format the number so it *\*prints\** with leading zeros, or you need to read it as a string. – markspace Oct 09 '18 at 18:37
  • 2
    Also see here, if you really need it to be an integer: https://stackoverflow.com/questions/473282/how-can-i-pad-an-integer-with-zeros-on-the-left – markspace Oct 09 '18 at 18:39
  • 4
    The values are being read as an `int` which doesn't store leading zeros. Search on formatting, or possibly read as a String. – Andrew S Oct 09 '18 at 18:39
  • what kind of output you are expecting from the program? – Rans Oct 09 '18 at 19:05

1 Answers1

6

Use scanner.next() instead of scanner.nextInt().

Using scanner.nextInt() will remove any leading zeros, since 0001 == 1.

Grant Foster
  • 716
  • 2
  • 12
  • 21