bordia bordia - 2 months ago 8
Java Question

A string length is not printing out correctly with 0 in front

I'm working on a program that will ask for the first

9
digits of an ISBN number (
d1d2d3d4d5d6d7d8d9
) that the user inputs and then prints out the number with a
10
th digit based on an equation:

(d1 × 1 + d2 × 2 + d3 × 3 + d4 × 4 + d5 × 5 + d6 × 6 + d7 × 7 + d8 × 8 + d9 × 9)%11)


If the checksum is
10
, the last digit is denoted as
X
according to the problem. If not, the last number is added onto the ISBN. I have the program working other than when the integer begins with a 0 when entered by the user.

Ex


Input: 113601267

Output: 1136012676


Ex.


Input: 013032342

Output: "This is an invalid ISBN Entry!"


Here's my code:

int ISBN, r, i;
String st;

Scanner keyboard;
keyboard = new Scanner(System.in);

System.out.println("Please enter the first 9 digits of your ISBN number:");
ISBN = keyboard.nextInt();

st = ("" + ISBN);

if (st.length() == 9){
r = (st.charAt(0) * 1 + st.charAt(1) * 2 + st.charAt(2) * 3 + st.charAt(3) * 4 + st.charAt(4) * 5 + st.charAt(5) * 6 + st.charAt(6) * 7 + st.charAt(7) * 8 + st.charAt(8) * 9);

if (r % 11 == 10){
System.out.println("Your ISBN Number is: " + ISBN + "X");
}
else {
System.out.println(st);
i = (ISBN * 10) + (r % 11);
System.out.println("Your ISBN Number is: " + i);
}
}
else {
System.out.println("This is an invalid ISBN entry!");
}


Where did I mess up, or what is going on?

Answer

You have two bugs:

  1. You should reformat your String to prepend 0 if needed.

  2. You have Strings. A String is composed of chars. If your first ISBN digit is 1, you'll actually do '1'*1. Since '1' is a char, you'll get the int value of the char, which is 49. What you have to do is subtract '0' from each char to get the actual int value of each char:

    int ISBN, r, i;
    String st;
    
    Scanner keyboard;
    keyboard = new Scanner(System.in);
    
    System.out.println("Please enter the first 9 digits of your ISBN number:");
    ISBN = keyboard.nextInt();
    
    st = String.format("%09d", ISBN); // fixes your 0-bug.
    
    if (st.length() == 9){
        r = ((st.charAt(0) - '0') * 1 // fixes your computation bug.
           + (st.charAt(1) - '0') * 2
           + (st.charAt(2) - '0') * 3
           + (st.charAt(3) - '0') * 4
           + (st.charAt(4) - '0') * 5
           + (st.charAt(5) - '0') * 6
           + (st.charAt(6) - '0') * 7
           + (st.charAt(7) - '0') * 8
           + (st.charAt(8) - '0') * 9);
    
        if (r % 11 == 10){
            System.out.println("Your ISBN Number is: " + ISBN + "X");
        }
        else {
            System.out.println(st);
            i = (ISBN * 10) + (r % 11);
            System.out.println("Your ISBN Number is: " + i);
        }
    
    }
    else {
        System.out.println("This is an invalid ISBN entry!");
    }
    

    }

Comments