Validate International Securities Identification Number: Difference between revisions

Content added Content deleted
(→‎{{header|Java}}: Fixed this example so the input and output now correspond. Embedded the luhnTest method in the ISIN class.)
Line 1,115: Line 1,115:


=={{header|Java}}==
=={{header|Java}}==
As the Luhn test method from the ''[[Luhn test of credit card numbers]]'' task is only a few lines, it has been embedded in the ISIN class for convenience.
{{incorrect|Java|Output isn't according to the input.}}
This now assumes that the existing Luhn algorithm implementation from the ''[[Luhn test of credit card numbers]]'' task is available in the same (default) package.


<lang java>public class ISIN {
<lang java>public class ISIN {

public static void main(String[] args) {
public static void main(String[] args) {
String[] isins = {
String[] isins = {
"US0378331005",
"US0378331005",
"US0373831005",
"US0373831005",
"U50378331005",
"U50378331005",
"US03378331005",
"US03378331005",
"AU0000XVGZA3",
"AU0000XVGZA3",
"AU0000VXGZA3",
"AU0000VXGZA3",
"FR0000988040",
"FR0000988040"
};
};
for (String isin : isins)
for (String isin : isins)
System.out.printf("%s is %s%n\n", isin, ISINtest(isin) ? "valid" : "not valid");
System.out.printf("%s is %s\n", isin, ISINtest(isin) ? "valid" : "not valid");
}
}

static boolean ISINtest(String isin) {
static boolean ISINtest(String isin) {
isin = isin.trim().toUpperCase();
isin = isin.trim().toUpperCase();

if (!isin.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$"))
if (!isin.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$"))
return false;
return false;

StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder();
for (char c : isin.substring(0, 12).toCharArray())
for (char c : isin.substring(0, 12).toCharArray())
sb.append(Character.digit(c, 36));
sb.append(Character.digit(c, 36));
return luhnTest(sb.toString());
}


return Luhn.luhnTest(sb.toString());
static boolean luhnTest(String number) {
int s1 = 0, s2 = 0;
String reverse = new StringBuffer(number).reverse().toString();
for (int i = 0; i < reverse.length(); i++){
int digit = Character.digit(reverse.charAt(i), 10);
//This is for odd digits, they are 1-indexed in the algorithm.
if (i % 2 == 0){
s1 += digit;
} else { // Add 2 * digit for 0-4, add 2 * digit - 9 for 5-9.
s2 += 2 * digit;
if(digit >= 5){
s2 -= 9;
}
}
}
return (s1 + s2) % 10 == 0;
}
}
}</lang>
}</lang>

<pre>US0378331005 is valid
<pre>US0378331005 is valid
US0373831009 is valid
US0373831005 is not valid
D56000543287 is not valid
U50378331005 is not valid
US03378331005 is not valid
AU0000XVGZA3 is valid
AU0000XVGZA3 is valid
AU0000VXGZA3 is valid
AU0000VXGZA3 is valid
GB0002634946 is valid
FR0000988040 is valid</pre>
US0373831005 is not valid</pre>


=={{header|Julia}}==
=={{header|Julia}}==