All pastes #2089617 Raw Edit

Anonymous

public text v1 · immutable
#2089617 ·published 2011-10-13 04:47 UTC
rendered paste body
public static boolean validateIsbn(String isbn){
	
	// check length
	if(isbn.length() != 10)
	{
		return false;
	}
	
	// validate characters
	int num;
	for(int i = 0; i < 10; i++)
	{
		num = Character.getNumericValue(isbn.charAt(i));
		if(num < 0 || num > 9)
		{

			// if it is the last digit, we can allow an 'X'
			if(i == 9 && isbn.charAt(i) == 'X')
			{
				continue;
			}
			
			
			return false;
		}
	}
	
	// calculate checksum
	int checkSum = 0;
	for(int i = 0; i < 10; i++)
	{
		num = Character.getNumericValue(isbn.charAt(i));
		if(i < 9)
		{
			checkSum += num * (10 - i);
		}
		else if(isbn.charAt(i) == 'X')
		{
			checkSum += 10;
		}
		else 
		{
			checkSum += num;
		}		
	}
	
	// validate checksum
	if(checkSum % 11 != 0)
	{
		return false;
	}

	return true;

}