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!