0
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number with 4 digits: ");
while(!scan.hasNextInt()){
    //If the next int is not an integer, it will allow you to input again until an int is recieved
    scan.next();
}
int n = scan.nextInt();
String strn = "" + n;

The issue I'm having is that when a user inputs a code with a zero as the first number, such as 0481, it's saved in the string as 481. How would I make sure a leading zero is counted in this case?

Spooks
  • 1
  • 1
    You are getting an `int` but expect to receive `string` ? Get a string from the input and check if its only digits later. No way you are getting a leading zero in an `int`. – VTodorov Oct 14 '17 at 00:30
  • @Spooks - You are missing the point. Use `next()` rather than `nextInt()`. – Stephen C Oct 14 '17 at 00:35
  • 1
    Leading zero for an int says "octal". Don't do it. https://stackoverflow.com/questions/565634/integer-with-leading-zeroes – duffymo Oct 14 '17 at 00:38
  • I got it now, thanks – Spooks Oct 14 '17 at 00:39

3 Answers3

0

Don't read ints. Use a string if you want leading zeros.

Try the following

String strn;
do { 
    strn = scan.nextLine();
    if (strn.matches("\\D") {
        // there's a non numeric value entered, repeat loop 
    } else { break; }
} while (true)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

If you want to keep the leading zeros you will need to use string instead, you can then use regex or checking each digit to make sure the number is valid.

If you want to add the leading zeros back in you will be better using String.format, like this

    int x = 55;
    String formatted = String.format("%04d", x);

This makes formatted contain 0055.

The reason you are having issues is that int just holds a number, and from a value perspective 05 and 5 are the same, so int stores them the same, and it is output as the least number of digits required by default.

jrtapsell
  • 6,719
  • 1
  • 26
  • 49
0

leading zeros is counted in the case of digit int val 0044 is always 44

try this:

Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number with 4 digits: ");
while(!scan.hasNextInt()){
    //If the next int is not an integer, it will allow you to input again 
    until an int is recieved
    scan.next();
}
String strn = scan.nextLine();
Amol Raje
  • 928
  • 3
  • 9
  • 16