Jay da science noob
Jay da science noob

Reputation: 23

Java methods isbn char conversion and output problems. Can't find out mistake in algorithm

I'm trying create a method which returns char type. The condition is this: system takes 9 digits from user input and calculate it. The method converts each char in the nextLine() input and computes the sum then take % 11. If the remainder is 10, method return 'X' and if the remainder is 0 through 9, then the method returns that digit but must be in char type. So far I'm lost at why it will always output '/' and nothing else. Please help me find out the mistake of my algorithms.

public static char getCheckSum(String isbn) {
    int sum = 0;
    char charSum;
    for (int i = 0; i < isbn.length(); i++) {
        int[] num = new int[isbn.length()]; 
        num[i] = Character.getNumericValue(i) * (i+1);
        sum = sum + num[i];
    }
    int last = (sum % 11);

    if (last == 10){
        charSum = (char) 88;
    } else {
        charSum = (char) (last + 48);
    }
    return charSum;

//this is the next part where it inserts hyphens just as a reference

public static String formatISBNWithHyphens(String isbn) {
    // original isbn:       123456789
    // possible new isbn:   1-234-56789-X
    char isbn10 = getCheckSum(isbn);
    String isbn10Str = isbn + Character.toString(isbn10);

//  char[] c = new char[isbn10Str.length()];    *leaving this here for future learning.
    String[] cStr = new String[isbn10Str.length()];
    String isbnStr = "";
    for (int i = 0; i < isbn10Str.length(); i++){
        cStr[i] = Character.toString(isbn10Str.charAt(i));
//      c[i] = isbn10Str.charAt(i);             *leaving this here for future learning.
        if (i == 0 || i == 3 || i == 8 ) {
            cStr[i] += '-';
         }

         isbnStr += cStr[i];
    }
    return isbnStr;
}

// The final outcome is always like this 321654987/ and 3-216-54987-/ it is supposed to be either numbers from 0 to 9 or X if remainder is 10.

Please help. Thanks a bunch.

Upvotes: 0

Views: 170

Answers (1)

Javy
Javy

Reputation: 954

I think the problem is here

for (int i = 0; i < isbn.length(); i++) {
    int[] num = new int[isbn.length()]; 
    num[i] = Character.getNumericValue(i) * (i+1);
    sum = sum + num[i];
}

The for cycle returning a result has no relationship with the isbn's content, the result just depends on the isbn string length!

so you can change the code to the following one below

for (int i = 0; i < isbn.length(); i++) {
        int[] num = new int[isbn.length()]; 
        num[i] = Character.getNumericValue(isbn.charAt(i));
        sum = sum + num[i];
}

the code above returns a result depending on the isbn's content

Upvotes: 1

Related Questions