1

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?

default locale
  • 13,035
  • 13
  • 56
  • 62
polaris
  • 339
  • 2
  • 14
  • 33
  • 1
    Even String input on conversion to int would have removed those zeroes I guess! – Am_I_Helpful Jul 18 '14 at 05:03
  • If the object is to validate some user input you need to keep the input as a string. You can then perform the validation on the string e.g. whether the value is an integer. – fipple Jul 18 '14 at 05:13
  • Probably, you can format it later. Take a look at [this question](http://stackoverflow.com/questions/275711/add-leading-zeroes-to-number-in-java?rq=1) I marked your question as a duplicate, but now I'm not really sure – default locale Jul 18 '14 at 05:36
  • 1
    What all the other said, and I'll just add the conclusion: no, that code cannot be finished to fulfill the requirements the way it is. But that's also a learning moment; the web is full of nonsense too. Try to stick to reputable sources for information and guidance. – Gimby Jul 18 '14 at 07:07
  • Thanks for the answers. I too thought that it cannot be done that way. I did myinput.nextString(). Then I manipulated the string character by character string.chartAt() to get the different digits. – polaris Jul 20 '14 at 01:11

2 Answers2

1

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(); " ?

Steve B.
  • 55,454
  • 12
  • 93
  • 132
0

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
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249