gpt4 book ai didi

java - 银行识别码 validator

转载 作者:行者123 更新时间:2023-12-02 06:16:00 25 4
gpt4 key购买 nike

我是 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");
}

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

提前致谢。

最佳答案

至少有一个错误。你的

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");
}

输出为“VALID”。

关于java - 银行识别码 validator ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21464495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com