2014-01-30 100 views
0

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

我相信這不是正確的方法,但它是一些東西。

在此先感謝。

+0

也許你添加了NSLog輸出,所以它更容易看到發生錯誤的位置。 – Volker

回答

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

,輸出爲「有效」。