利用校验位检查学生输入的学号是否正确
package checkTheID; import java.util.Scanner; public class CheckTheID { //学号6位数字,校验位第7位。也可以修改。 //用户输入学号及校验位,程序检测用户输入的学号是否正确。 //校验位=(1*(第1位数字)+2*(第2位数字)+3*(第3位数字) //+4*(第4位数字)+5*(第5位数字)+6*(第6位数字))%10 public static final int IDLENGTH = 7; public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("input your id (" + IDLENGTH + " bit): "); int id = console.nextInt(); int[] s = new int[IDLENGTH]; s = computeEverBit(id); int checkbit; checkbit = getCheckBit(s); if(checkbit != s[IDLENGTH - 1]) System.out.println("input the wrong id!Please input again:"); else System.out.println("there is 90% possibility that you input the right id!"); } //输入:学号(整数值),输出:返回数组,每个元素即为学号的每个数字 public static int[] computeEverBit(int id) { int[] s = new int[IDLENGTH]; for(int i = 0;i < IDLENGTH;i++) { s[i] = id / (int)Math.pow(10,IDLENGTH-1-i); id = id % (int)Math.pow(10,IDLENGTH-1-i); } return s; } //输入:数组,输出:返回根据前六个元素得到校验位 public static int getCheckBit(int[] s) { int checkbit,sum = 0; for(int i = 1;i<= IDLENGTH - 1;i++) sum += s[i-1]*i; checkbit =sum % 10; return checkbit; } }