Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding individual digits from a string

Tags:

java

I'm trying to add 13 individual digits from a string together. I thought using a while loop would be the best way to do this, but I think I messed something up. Here's my code:

import java.util.Scanner;

public class ISBNChecker{
    public static void main(String [] args){
        String isbnNumber;
        int isbnTotal= 0;
        int index = 0;

        Scanner scnr = new Scanner(System.in);
        System.out.println("Enter a 13 digit ISBN Number:");
        isbnNumber = scnr.nextLine();
        if (isbnNumber.length() != 13) {
            System.out.println("Error- 13 numerical digits required");
        }
        char num = isbnNumber.charAt(index);
        while (index <13) {
        if (index % 2 == 0) {
            isbnTotal = isbnTotal + num;
            index =index + 1;
        }
        else { 
            isbnTotal = isbnTotal + (3 * num);
            index = index + 1;
        }
        }
        System.out.println(isbnTotal);
        if (isbnTotal % 10 == 0) {
            System.out.println("Valid ISBN Number");
        }
        else {
            System.out.println("Invalid ISBN Number");
        }
    }
}

I'm using the input 9780306406157, which should be an invalid ISBN Number. The value of isbnTotal at the end of the program should be 100, but instead, it is 1425. Any help in figuring out how to fix it would be appreciated. Also, the formula I'm using for the problem is x1 + 3x2 + x3 + 3x4 ... +x 13 for reference!

like image 611
jenna crist Avatar asked May 25 '26 20:05

jenna crist


1 Answers

I found your bug, you made some mistake.

int index = 0;
while (index < 13) {
    char num = (char) (isbnNumber.charAt(index) - '0');
    
    if (index % 2 == 0) {
        isbnTotal = isbnTotal + num;
    } else {
        isbnTotal = isbnTotal + (3 * num);
    }
    
    index++;
}

Problem #1

The code

 char num = isbnNumber.charAt(index);

Was not in your while loop, causing your code to always run with the same character.

Problem #2

When doing

char num = isbnNumber.charAt(index);

You are actually getting the ASCII value of the character. What you cant to get is the value of the number right ? So you have to do:

char num = (char) (isbnNumber.charAt(index) - '0');

Notice that the zero is between two single quote, that because we want the value of the ZERO ASCII CHARACTER (which is 38).

'1' - '0' = 1

'9' - '0' = 9

EDIT: I forgot to mention that you should check before if the character is a number, else you will maybe try to do something like 'A' - '0' which will be equal to 17

like image 120
Enzo Caceres Avatar answered May 28 '26 09:05

Enzo Caceres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!