Reputation: 339
If I input an int value, is it possible to keep a leading zero. For example if I input 0123, is there a way to pass that zero without formatting the data. I came across an exercise on a website which asks to enter an isbn number as an int and validate it. The initial code given is the following.
import java.util.Scanner;
public class isbncheck {
public static void main(String[] args) {
int num= 0;
int digit = 0;
int sum = 0;
System.out.println("Enter ISBN Number:");
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
/*
Your code here
*/
System.out.println("The ISBN number is:");
}
}
the link to the website is http://www.programmr.com/challenges/isbn-validation-1
If I wanted to take the first digit of an input and do something with it, I cannot if the first integer is a 0. To test the code the input is 0201314525. However I lose the initial zero and then I cannot make the code work. I used a String input instead of an int which I can then manipulate to do what I want. Is it possible to complete the code given the way it's being presented?
Upvotes: 1
Views: 7229
Reputation: 201537
No. int
cannot be inherently formated, you could store it as a String. Or you will need to String#format() the int
to have leading zeros,
String isbn = String.format("%013d", num); // 0 fill to 13 digits num
Upvotes: 0
Reputation: 57333
You will need to preserve the value as a String. You should do this anyway with something like an ISBN number since its value is not its magnitude but its string representation.
Why not just use " String num = sc.next(); " ?
Upvotes: 1