Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /*
- * Checks if entered SINs are valid.
- *
- * Based off MonkeyShrapnel's code
- *
- * SINs verified using Luhn algorithm:
- * https://en.wikipedia.org/wiki/Social_Insurance_Number#Validation
- *
- */
- public class sinValidator
- {
- final static int[] mult = {1,2,1,2,1,2,1,2,1}; //constant array for multiplying
- public static void main(String[] args) {
- String[] sin = new String[100]; //array of strings for storing SINs
- Scanner kb = new Scanner(System.in); //scanner
- int numSins = 0; //initialize number of SINs input to 0
- System.out.println("Please enter SINs"
- +", enter stop after last one"); //prompt
- String aSin = kb.next(); //read first SIN
- while(!aSin.equals("stop")) { //loop until "stop"
- sin[numSins++] = aSin; //set item in array to number input, increment numSins
- aSin = kb.next(); //read input from user
- }
- for (int i = 0; i < numSins; i++) { //loop through once for every SIN entered
- int sum = 0; //sum, initialized to 0
- int[] d = new int[9]; //initialize array of 9 integers
- System.out.print(sin[i] + " - "); //print out current SIN in list
- sin[i] = sin[i].replace("-", ""); //remove all hyphens
- if(sin[i].length() == 9){ //only check if current string is 9 characters long
- char[] cSin = sin[i].toCharArray(); //create array of characters from string
- for(int j = 0; j < 9; j++)
- d[j] = Character.getNumericValue(cSin[j]); //set all values in d[] to numerical values of cSin
- //math
- for (int j=0; j<9; j++) {
- int prod = d[j] * mult[j];
- if (prod > 9)
- prod = (prod/10)+(prod%10);
- sum += prod;
- }
- //print whether the string is a valid SIN or not
- if (sum % 10 == 0)
- System.out.println("Valid");
- else
- System.out.println("Invalid");
- }
- else
- System.out.println("Invalid"); //string wasn't 9 chars long, invalid
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement