Advertisement
Ashanmaril

SIN validate

Jun 12th, 2015
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.07 KB | None | 0 0
  1. import java.util.Scanner;
  2. /*
  3.  * Checks if entered SINs are valid.
  4.  *
  5.  * Based off MonkeyShrapnel's code
  6.  *
  7.  * SINs verified using Luhn algorithm:
  8.  * https://en.wikipedia.org/wiki/Social_Insurance_Number#Validation
  9.  *
  10.  */
  11. public class sinValidator
  12. {
  13.     final static int[] mult = {1,2,1,2,1,2,1,2,1}; //constant array for multiplying
  14.    
  15.     public static void main(String[] args) {
  16.         String[] sin = new String[100]; //array of strings for storing SINs
  17.         Scanner kb = new Scanner(System.in); //scanner
  18.         int numSins = 0; //initialize number of SINs input to 0
  19.        
  20.         System.out.println("Please enter SINs"
  21.         +", enter stop after last one"); //prompt
  22.        
  23.         String aSin = kb.next(); //read first SIN
  24.     while(!aSin.equals("stop")) { //loop until "stop"
  25.         sin[numSins++] = aSin; //set item in array to number input, increment numSins
  26.         aSin = kb.next(); //read input from user
  27.         }
  28.        
  29.         for (int i = 0; i < numSins; i++) { //loop through once for every SIN entered
  30.             int sum = 0; //sum, initialized to 0
  31.             int[] d = new int[9]; //initialize array of 9 integers
  32.            
  33.             System.out.print(sin[i] + " - "); //print out current SIN in list
  34.            
  35.         sin[i] = sin[i].replace("-", ""); //remove all hyphens
  36.            
  37.     if(sin[i].length() == 9){ //only check if current string is 9 characters long
  38.            
  39.                 char[] cSin = sin[i].toCharArray(); //create array of characters from string
  40.                
  41.         for(int j = 0; j < 9; j++)
  42.             d[j] = Character.getNumericValue(cSin[j]); //set all values in d[] to numerical values of cSin
  43.                
  44.                 //math
  45.         for (int j=0; j<9; j++) {
  46.             int prod = d[j] * mult[j];
  47.             if (prod > 9)
  48.             prod = (prod/10)+(prod%10);
  49.             sum += prod;
  50.         }
  51.                
  52.         //print whether the string is a valid SIN or not
  53.         if (sum % 10 == 0)  
  54.             System.out.println("Valid");
  55.         else
  56.             System.out.println("Invalid");
  57.             }
  58.             else
  59.                 System.out.println("Invalid"); //string wasn't 9 chars long, invalid
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement