银行识别号码验证器

时间:2014-01-30 18:20:28

标签: java objective-c

我是Objective-c的新手,我不太了解Java,我的问题是:

我在Java中使用此代码来验证银行标识号:

 public static boolean isValidNIB(String nib) {
    char[] toValidate = nib.substring(0, 19).toCharArray();
    Integer checkDigit = Integer.valueOf(nib.substring(19));
    Integer[] wi = { 73, 17, 89, 38, 62, 45, 53, 15, 50, 5, 49, 34, 81, 76, 27, 90, 9, 30, 3 };
    Integer sum = 0;
    for (int i = 0; i < 19; i++) {
        sum += Character.digit(toValidate[i], 10) * wi[i];
    }
    return checkDigit.equals(98 - (sum % 97));
}

我需要将此代码转换为objective-c,问题是我无法使其工作...

这是我尝试将java代码翻译成objective-c:

NSString *nib = @"003500970000199613031"; //UNICEF NIB :P

//transforms nsstring to array of chars
NSMutableArray *chars = [[NSMutableArray alloc] initWithCapacity:[nib length]];
for (int i=0; i < [nib length]; i++) {
    NSString *ichar  = [NSString stringWithFormat:@"%C", [nib characterAtIndex:i]];
    [chars addObject:ichar];
}

NSLog(@"array nib = %@",chars);


//retrieves the first 19 chars
NSMutableArray *toValidate = [[NSMutableArray alloc] init];
for (int i=0; i < chars.count; i++) {

    if (i <= 19) {
        [toValidate addObject:[chars objectAtIndex:i]];
    }
}

NSLog(@"array toValidate = %@",toValidate);

NSString * checkDigit = [nib substringWithRange:NSMakeRange(19, 1)];


NSArray *weight = [NSArray arrayWithObjects:@"73", @"17", @"89", @"38", @"62", @"45", @"53", @"15", @"50", @"5", @"49", @"34", @"81", @"76", @"27", @"90", @"9", @"30", @"3", nil];



NSInteger sum = 0;
for (int i = 0; i < weight.count ; i++) {

    sum += [[toValidate objectAtIndex:i] integerValue] * [[weight objectAtIndex:i] integerValue];

}

if (checkDigit.integerValue == (98 -(sum % 97))) {
    NSLog(@"VALD");
}else{
    NSLog(@"NOT VALID");
}

我确信这不是正确的方法,但它确实存在。

先谢谢。

1 个答案:

答案 0 :(得分:2)

至少有一个错误。你的

NSString * checkDigit = [nib substringWithRange:NSMakeRange(19, 1)];

仅从标识号返回一个字符(位置19)(在这种情况下) “3”),但

Integer checkDigit = Integer.valueOf(nib.substring(19));

计算位置19处的子串开始的值(在本例中为“31”)。 因此,计算的校验和与预期值不匹配。

但是你的代码中还有很多不必要的计算,而且还有 没有理由将权重存储在字符串数组中。 该方法可以缩短为:

NSString *nib = @"003500970000199613031";

int weight[] = { 73, 17, 89, 38, 62, 45, 53, 15, 50, 5, 49, 34, 81, 76, 27, 90, 9, 30, 3 };
NSInteger sum = 0;
for (int i = 0; i < 19; i++) {
    sum += [[nib substringWithRange:NSMakeRange(i, 1)] intValue] * weight[i];
}
int checkDigit = [[nib substringFromIndex:19] intValue];
if (checkDigit == (98 - (sum % 97))) {
    NSLog(@"VALID");
} else {
    NSLog(@"NOT VALID");
}

输出为“有效”。